
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using DocumentFormat.OpenXml.Spreadsheet;
    using Domain.Configurations;
    using Domain.Helpers;
    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Api.Senders;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library;
    using Hims.Shared.UserModels.PediatricEncounter;
    using Hims.Shared.UserModels.Slots;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using Shared.DataFilters;
    using Shared.Library.Enums;
    using Shared.UserModels;
    using Utilities;
    using pediatric = Shared.UserModels.PediatricEncounter;


    /// <summary>
    /// The internal medicine controller.
    /// </summary>
    [Route("api/pediatric-encounter")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class PediatricEncounterController : BaseController
    {
        /// <summary>
        /// the provider service
        /// </summary>
        private readonly IEncounterService encounterServices;

        /// <summary>
        /// The push notification helper.
        /// </summary>
        private readonly IPushNotificationHelper pushNotificationHelper;

        /// <summary>
        /// The account session services.
        /// </summary>
        private readonly IAccountSessionService accountSessionServices;


        /// <summary>
        /// The account session services.
        /// </summary>
        private readonly IPediatricEncounterService pediatricEncounterService;


        /// <summary>
        /// the aes helper
        /// </summary>
        private readonly IAESHelper aesHelper;

        /// <summary>
        /// The appointments services.
        /// </summary>
        private readonly IAppointmentService appointmentsServices;

        /// <summary>
        /// The account service.
        /// </summary>
        private readonly IAccountService accountService;

        /// <summary>
        /// The amazon s3 helper.
        /// </summary>
        private readonly IDocumentHelper documentHelper;
        private readonly ISMSSender smsSender;
        /// <summary>
        /// The configuration.
        /// </summary>
        private readonly IAmazonS3Configuration configuration;
        private readonly IWhatsAppSMSSender whatsAppSMSSender;

        /// <summary>
        /// The setting service
        /// </summary>
        private readonly ISettingService settingService;
        /// <inheritdoc />
        /// <summary>
        /// The setting service
        /// </summary>
        private readonly IAuditLogService auditLogService;
        /// <inheritdoc />
        /// /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;
        public PediatricEncounterController(
            IPediatricEncounterService pediatricEncounterService,
            IAppointmentService appointmentsServices,
            IAESHelper aesHelper,
            IDocumentHelper documentHelper,
            IEncounterService encounterServices,
            IPushNotificationHelper pushNotificationHelper,
            IAccountSessionService accountSessionServices,
            IAmazonS3Configuration configuration,
            IAccountService accountService, IWhatsAppSMSSender whatsAppSMSSender, ISMSSender smsSender, ISettingService settingService, IAuditLogService auditLogService)
        {
            this.pediatricEncounterService = pediatricEncounterService;
            this.appointmentsServices = appointmentsServices;
            this.aesHelper = aesHelper;
            this.documentHelper = documentHelper;
            this.configuration = configuration;
            this.accountService = accountService;
            this.encounterServices = encounterServices;
            this.pushNotificationHelper = pushNotificationHelper;
            this.accountSessionServices = accountSessionServices;
            this.whatsAppSMSSender = whatsAppSMSSender;
            this.smsSender = smsSender;
            this.settingService = settingService;
            this.auditLogService = auditLogService;
        }



        /// <summary>
        /// The modify async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("modify")]
        [ProducesResponseType(typeof(int), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyAsync([FromBody] pediatric.InsertModel model, [FromHeader] LocationHeader header)
        {
            model = (pediatric.InsertModel)EmptyFilter.Handler(model);

            var pediatricEncounterId = model.PediatricEncounterId == 0 ? await this.pediatricEncounterService.AddAsync(model) : await this.pediatricEncounterService.UpdateAsync(model);
            var patientDetails = this.unitOfWork.Patients.Find(s => s.PatientId== model.PatientId);

            if (pediatricEncounterId!=null)
            {
                try
                {
                    var auditLog = new AuditLogModel
                {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.PediatricEncounter,
                        LogDate = DateTime.Now,
                        LogFrom = (short)model.LoginRoleId,
                        LogDescription = $"<b>{model.CreatedByName}<b> has added <b>{(model.PediatricEncounterId>0? "'Updated'" : "'Added'")}</b> to the Patient UMR NO. <strong>{patientDetails.UMRNo}</strong> ",
                        LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogService.LogAsync(auditLog);

                }

                catch (Exception ex)
                {
                    throw;
                }

            }

            switch (pediatricEncounterId.Response)
            {
                case 0:
                    return this.ServerError();
                default:
                    var basicDetails = await this.encounterServices.GetBasicAppointmentDetails(model.AppointmentId, model.IsAdmission);
                    await this.appointmentsServices.UpdateEncounterTypeAsync(model.AppointmentId,
                        (int)EncounterTypes.PediatricEncounter, model.IsAdmission);
                    if (model.Type == PediatricEncounterType.PediatricGuide)
                    {
                        var appointment = await this.appointmentsServices.FindAsync(model.AppointmentId);
                        dynamic item = JsonConvert.DeserializeObject(model.JsonString);
                        //dynamic dietGuidelines = item.dietGuidLines;

                       
                            foreach (var record in item)
                            {
                                string pdfLink = record["optionalText"];
                                var contentType = record["value"];
                                dynamic dietName = record["name"];
                                dietName = Convert.ToString(dietName);
                                var dietId = record["id"];
                                string link = $@"{dietId}/{pdfLink}";
                                var WhatsAppMessageSetting = await this.settingService.FetchAsync("WhatsAppMsgService", null, null);
                                var WhatsAppMessage = WhatsAppMessageSetting.ToList();
                                if ((bool)WhatsAppMessage[0].Active)
                                {
                                    var send = await this.whatsAppSMSSender.SendLabReportWhatsAppMessage(appointment.PatientMobile, appointment.PatientName, dietName, link);
                                }
                                var response = await this.smsSender.SendPdfLinkSms(appointment.PatientMobile, appointment.PatientName, link);
                            }
                           
                      
                    }
                    return this.Success(pediatricEncounterId.Response);
            }
        }

        /// <summary>
        /// To find ob encounter dashboard
        /// </summary>
        /// <param name="model" >
        /// The encounter filter model.
        /// </param>
        /// <returns>
        /// The encounter model.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("find-dashboard")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindDashboardAsync([FromBody] PediatricEncounterFilterModel model)
        {
            model = (PediatricEncounterFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var response = await this.pediatricEncounterService.FindDashboardAsync(appointmentId, model.Type, model.IsAdmission);
            if (response != null)
            {
                response.EncryptedAppointmentId = this.aesHelper.Encode(appointmentId.ToString());
            }
            return this.Success(response);
        }

        /// <summary>
        /// The find gyn encounter.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("find")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindAsync([FromBody] PediatricEncounterFilterModel model)
        {
            model = (PediatricEncounterFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var obEncounter = await this.pediatricEncounterService.FindAsync(appointmentId, model.IsAdmission);
            var providerId = !string.IsNullOrEmpty(model.EncryptedProviderId)
                ? Convert.ToInt32(this.aesHelper.Decode(model.EncryptedProviderId))
                : 0;
            var patientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));
            var appointmentList = new List<AppointmentModel>();
            var oldAppointment = new PreviousAppointmentModel();

            if (!model.IsAdmission)
            {
                var appointments = await this.appointmentsServices.FindByPatientAsync(patientId, providerId);
                appointmentList = appointments.ToList();

                foreach (var item in appointmentList)
                {
                    item.EncryptedAppointmentId = this.aesHelper.Encode(item.AppointmentId.ToString());
                    item.EncryptedPatientId = model.EncryptedPatientId;
                    item.AppointmentTimeString = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"))
                        .Add(item.AppointmentTime).ToString("hh:mm tt");
                }
            }

            return this.Success(new { Dashboard = obEncounter, Appointments = appointmentList, OldAppointment = oldAppointment });
        }

        /// <summary>
        /// The find full transcript async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("find-full-transcript")]
        [ProducesResponseType(typeof(GynEncounterFullTranscriptModel), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindFullTranscriptAsync([FromBody] PediatricEncounterFilterModel model)
        {
            model = (PediatricEncounterFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var pediatricEncounterFullTranscript = await this.pediatricEncounterService.FindFullTranscriptAsync(appointmentId);
            if (pediatricEncounterFullTranscript == null || pediatricEncounterFullTranscript.PediatricEncounterId == 0)
            {
                return this.BadRequest("Sorry! We don't have a encounter in the system.");
            }

            var additionalData = await this.encounterServices.GetAdditionalProviderDataAsync(appointmentId);

            if (additionalData != null)
            {
                pediatricEncounterFullTranscript.Educations = additionalData.Educations;
                pediatricEncounterFullTranscript.ProviderName = additionalData.ProviderName;
                pediatricEncounterFullTranscript.ProviderNo = additionalData.ProviderNo;
                pediatricEncounterFullTranscript.SpecializationName = additionalData.SpecializationName;
                pediatricEncounterFullTranscript.PracticeName = additionalData.PracticeName;
                pediatricEncounterFullTranscript.PracticeLocation = additionalData.PracticeLocation;
                pediatricEncounterFullTranscript.Signature = additionalData.Signature;
                pediatricEncounterFullTranscript.ClinicPicture = additionalData.ClinicPicture;
            }

            pediatricEncounterFullTranscript.AppointmentTimeString = Convert
                .ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Add(pediatricEncounterFullTranscript.AppointmentTime)
                .ToString("hh:mm tt");
            return this.Success(pediatricEncounterFullTranscript);
        }
        ///// <summary>
        ///// To find ob encounter dashboard
        ///// </summary>
        ///// <param name="model" >
        ///// The encounter filter model.
        ///// </param>
        ///// <returns>
        ///// The encounter model.
        ///// </returns>
        //[HttpGet]
        //[Authorize]
        //[Route("calculate-edd")]
        //[ProducesResponseType(typeof(EncounterResource), 200)]
        //[ProducesResponseType(500)]
        //public async Task<ActionResult> CalculateEDD(string value)
        //{

        //    var lmp = Convert.ToDateTime(value);
        //    var edd = lmp.AddDays(280);
        //    var eddcal = Convert.ToDateTime(edd).ToString("MM/dd/yyyy");
        //    return this.Success(eddcal);
        //}
        /// <summary>
        /// To calculate GA
        /// </summary>
        /// <param name="model" >
        /// The encounter filter model.
        /// </param>
        /// <returns>
        /// The encounter model.
        /// </returns>
        //[HttpGet]
        //[Authorize]
        //[Route("calculate-ga")]
        //[ProducesResponseType(typeof(EncounterResource), 200)]
        //[ProducesResponseType(500)]
        //public async Task<ActionResult> CalculateGA(string value)
        //{

        //    var today = DateTime.Now;
        //    var lmp = Convert.ToDateTime(value);
        //    var calculatediff = lmp.Subtract(today).TotalDays;
        //    var calga = (today.Day - lmp.Day);
        //    var ga = Math.Round(calculatediff / 7);
        //    return this.Success(ga);

        //}

        /// To calculate GA
        /// </summary>
        /// <param name="model" >
        /// The encounter filter model.
        /// </param>
        /// <returns>
        /// The encounter model.
        /// </returns>
        [HttpGet]
        [Authorize]
        [Route("calculate-ga")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> CalculateGA(string value)
        {

            var today = DateTime.Now;
            var dob = Convert.ToDateTime(value);
            var calculatediff = 0.0;


            calculatediff = today.Subtract(dob).TotalDays;


            var ga = Math.Round((calculatediff / 7), 1);
            return this.Success(ga);

        }
        [HttpGet]
        [Authorize]
        [Route("find-visitNo")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindVisitNo(int patientId)
        {
            var response = await this.pediatricEncounterService.FetchVisitNoAsync(patientId);
            return this.Success(response);
        }

        /// <summary>
        /// Fetches the pediatric measurement data asynchronous.
        /// </summary>
        /// <param name="patientId">The patient identifier.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("fetch-patient-measurement-history")]
        public async Task<ActionResult> FetchPediatricMeasurementDataAsync(int patientId)
        {
            if (patientId == 0) { return this.BadRequest("Invalid patient."); }
            var response = await this.pediatricEncounterService.FetchPediatricMeasurementHistoryAsync(patientId);
            return this.Success(response);
        }
    }

}



