using Hims.Api.Senders;
using Hims.Api.Utilities;
using Hims.Domain.Configurations;
using Hims.Domain.Entities;
using Hims.Domain.Helpers;
using Hims.Domain.Services;
using Hims.Shared.DataFilters;
using Hims.Shared.EntityModels;
using Hims.Shared.Library;
using Hims.Shared.Library.Enums;
using Hims.Shared.UserModels.DietEncounter;
using Hims.Shared.UserModels.OBEncounter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;

namespace Hims.Api.Controllers
{

    using diet = Shared.UserModels.DietEncounter;

    /// <summary>
    /// The internal medicine controller.
    /// </summary>
    [Route("api/diet-plan-encounter")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class DietEncouterController : BaseController
    {
        /// <summary>
        /// The account session services.
        /// </summary>
        private readonly IDietEncounterService dietEncounterService;

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

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

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

        /// <summary>
        /// 
        /// </summary>
        private readonly IEncounterService encounterServices;

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

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


        /// <summary>
        /// The amazon s3 helper.
        /// </summary>
        private readonly IDocumentHelper documentHelper;

        /// <summary>
        /// The configuration.
        /// </summary>
        private readonly IAmazonS3Configuration configuration;
        /// <summary>
        /// The SMS sender.
        /// </summary>
        private readonly ISMSSender smsSender;

        /// <summary>
        /// The application configuration.
        /// </summary>
        private readonly IApplicationConfiguration applicationConfiguration;
        /// <summary>
        /// The whats application SMS sender
        /// </summary>
        private readonly IWhatsAppSMSSender whatsAppSMSSender;
        private readonly IFtpUploadHelper ftpUploadHelper;

        /// <summary>
        /// The setting service
        /// </summary>
        private readonly ISettingService settingService;

        public DietEncouterController(
           IDietEncounterService dietEncounterService,
            IAppointmentService appointmentsServices,
            IAESHelper aesHelper,
            IDocumentHelper documentHelper,
            IEncounterService encounterServices,
            IPushNotificationHelper pushNotificationHelper,
            IAccountSessionService accountSessionServices,
            IAmazonS3Configuration configuration,
            IAccountService accountService,
            IApplicationConfiguration applicationConfiguration,
            ISMSSender smsSender,
            IWhatsAppSMSSender whatsAppSMSSender,
            IFtpUploadHelper ftpUploadHelper,
            ISettingService settingService)
        {
            this.dietEncounterService = dietEncounterService;
            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.applicationConfiguration = applicationConfiguration;
            this.smsSender = smsSender;
            this.whatsAppSMSSender = whatsAppSMSSender;
            this.ftpUploadHelper = ftpUploadHelper;
            this.settingService = settingService;
        }


        [HttpPost]
        [Authorize]
        [Route("modify")]
        [ProducesResponseType(typeof(int), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyAsync([FromBody] diet.InsertModel model)
        {
            model = (diet.InsertModel)EmptyFilter.Handler(model);
            var dietEncounterId = model.DietEncounterId == 0 ? await this.dietEncounterService.AddAsync(model) : await this.dietEncounterService.UpdateAsync(model);
            switch (dietEncounterId.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.DietEncounter, model.IsAdmission);
                    if (model.Type == DietEncounterType.DietGuideLines)
                    {
                        var appointment = await this.appointmentsServices.FindAsync(model.AppointmentId);
                        dynamic item = JsonConvert.DeserializeObject(model.JsonString);
                        //dynamic dietGuidelines = item.dietGuidLines;

                        try
                        {
                            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"];
                                //if(contentType== "application/pdf")
                                //{
                                //    await this.ftpUploadHelper.DownloadBase64DataAsync(pdfLink);
                                //}
                                //else
                                //{
                                //    await this.ftpUploadHelper.DownloadSmallFilesAsync(pdfLink);
                                //}

                                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);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }

                    }
                    return this.Success(dietEncounterId.Response);
            }
        }
        [HttpPost]
        [Route("find-dashboard")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindDashboardAsync([FromBody] DietEncounterFiltersModel model)
        {
            model = (DietEncounterFiltersModel)EmptyFilter.Handler(model);
            if (model.EncryptedAppointmentId != null)
            {
                model.AppointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));

            }
            var response = await this.dietEncounterService.FindDashboardAsync(model.AppointmentId, model.Type, model.IsAdmission);
            if (response != null)
            {
                response.EncryptedAppointmentId = this.aesHelper.Encode(model.AppointmentId.ToString());
            }
            return this.Success(response);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Route("find")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindAsync([FromBody] DietEncounterFiltersModel model)
        {
            model = (DietEncounterFiltersModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var dietEncounter = await this.dietEncounterService.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 = dietEncounter, Appointments = appointmentList, OldAppointment = oldAppointment });
        }

        /// <summary>
        /// Fetches all asynchronous.
        /// </summary>
        /// <param name="patientId">The model.</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Route("visit-no")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindVisitNo(int patientId)
        {
            var response = await this.dietEncounterService.FetchVisitNoAsync(patientId);
            return this.Success(response);
        }

        /// <summary>
        /// To find ob encounter dashboard
        /// </summary>
        /// <param name="model" >
        /// The encounter filter model.
        /// </param>
        /// <returns>
        /// The encounter model.
        /// </returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("find-prescription")]
        [ProducesResponseType(typeof(GynEncounterFullTranscriptModel), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindPrescription([FromBody] DietEncounterFiltersModel model)
        {
            model = (DietEncounterFiltersModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var dietEncounterFullTrascript = await this.dietEncounterService.FindPrescriptionAsync(appointmentId);
            if (dietEncounterFullTrascript == null || dietEncounterFullTrascript.DietEncounterId == 0)
            {
                return this.BadRequest("Sorry! We don't have a encounter in the system.");
            }

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

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

            dietEncounterFullTrascript.AppointmentTimeString = Convert
                .ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Add(dietEncounterFullTrascript.AppointmentTime)
                .ToString("hh:mm tt");
            return this.Success(dietEncounterFullTrascript);
        }

        /// <summary>
        /// To find ob encounter dashboard
        /// </summary>
        /// <param name="model" >
        /// The encounter filter model.
        /// </param>
        /// <returns>
        /// The encounter model.
        /// </returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("find-gpla")]
        [ProducesResponseType(typeof(GynEncounterFullTranscriptModel), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindGpla([FromBody] DietEncounterFiltersModel model)
        {

            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var dietEncounterFullTrascript = await this.dietEncounterService.FindGpla(appointmentId);

            return this.Success(dietEncounterFullTrascript);
        }

    }
}
