
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.Entities;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library;
    using Hims.Shared.UserModels.NeonatalIPEncounter;
    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 neonatal = Shared.UserModels.NeonatalIPEncounter;


    /// <summary>
    /// The internal medicine controller.
    /// </summary>
    [Route("api/neonatal-ip-encounter")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class NeonatalIPEncounterController : 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 INeonatalIPEncounterService neonatalIPEncounterService;


        /// <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 NeonatalIPEncounterController(
            INeonatalIPEncounterService neonatalIPEncounterService,
            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.neonatalIPEncounterService = neonatalIPEncounterService;
            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] neonatal.InsertModel model, [FromHeader] LocationHeader header)
        {
            model = (neonatal.InsertModel)EmptyFilter.Handler(model);

            var neonatalIPEncounterId = model.NeonatalIPEncounterId == 0 ? await this.neonatalIPEncounterService.AddAsync(model) : await this.neonatalIPEncounterService.UpdateAsync(model);
            var patientDetails = this.unitOfWork.Patients.Find(s => s.PatientId == model.PatientId);

            if (neonatalIPEncounterId != null)
            {


            }

            switch (neonatalIPEncounterId.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.NeonatalIPEncounter, model.IsAdmission);

                    return this.Success(neonatalIPEncounterId.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] NeonatalIPFilterModel model)
        {
            model = (NeonatalIPFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var response = await this.neonatalIPEncounterService.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] NeonatalIPFilterModel model)
        {
            model = (NeonatalIPFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var obEncounter = await this.neonatalIPEncounterService.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.neonatalIPEncounterService.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);
//        }
//    }

//}



