using System.Collections.Generic;

namespace Hims.Api.Controllers
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain.Configurations;
    using Domain.Helpers;
    using Domain.Services;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Models.InternalMedicine;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library;
    using Shared.Library.Enums;
    using Shared.UserModels;
    using Shared.UserModels.Filters;
    using Utilities;
    using Hims.Api.Models;
    using Hims.Api.Helper;
    using Hims.Api.Models.GynEncounter;

    /// <summary>
    /// The internal medicine controller.
    /// </summary>
    [Authorize]
    [Route("api/emergency-encounter")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class EmegencyEncounterController : 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 IEmergencyEncounterService emergencyEncounterService;


        /// <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;

        /// <summary>
        /// The configuration.
        /// </summary>
        private readonly IAmazonS3Configuration configuration;

        /// <inheritdoc />
        public EmegencyEncounterController(
            IEmergencyEncounterService emergencyEncounterService,
            IAppointmentService appointmentsServices,
            IAESHelper aesHelper,
            IDocumentHelper documentHelper,
            IEncounterService encounterServices,
            IPushNotificationHelper pushNotificationHelper,
            IAccountSessionService accountSessionServices,
            IAmazonS3Configuration configuration,
            IAccountService accountService)
        {
            this.emergencyEncounterService = emergencyEncounterService;
            this.appointmentsServices = appointmentsServices;
            this.aesHelper = aesHelper;
            this.documentHelper = documentHelper;
            this.configuration = configuration;
            this.accountService = accountService;
            this.encounterServices = encounterServices;
            this.pushNotificationHelper = pushNotificationHelper;
            this.accountSessionServices = accountSessionServices;
        }



        /// <summary>
        /// The modify async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("modify")]
        [ProducesResponseType(typeof(int), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyAsync([FromBody] EmergencyEncounterModifyModel model)
        {
            model = (EmergencyEncounterModifyModel)EmptyFilter.Handler(model);
            var encounterId = model.EmergencyEncounterId == 0 ? await this.emergencyEncounterService.AddAsync(model) : await this.emergencyEncounterService.UpdateAsync(model);
            switch (encounterId.Response)
            {
                case 0:
                    return this.ServerError();
                default:
                    var basicDetails = await this.encounterServices.GetBasicAppointmentDetails(model.AppointmentId, model.IsAdmission);
                    var appointmentDetails = await this.appointmentsServices.FindAppointmentAsync(model.AppointmentId, model.IsAdmission);
                    await this.appointmentsServices.UpdateEmergencyTypeAsync(model.AppointmentId);
                    if (model.Type == EmergencyEncounterType.EmergencyTriage)
                    {
                        dynamic parsedData = JsonConvert.DeserializeObject(model.JsonString);
                        var typeOfEncounter = parsedData.typeOfVisit;
                        if (typeOfEncounter == "Gynaec" || typeOfEncounter == "Pre Pregnancy")
                        {
                            await this.appointmentsServices.UpdateEncounterTypeAsync(model.AppointmentId,
                                (int)EncounterTypes.GynEncounter, model.IsAdmission);
                        }
                        else if (typeOfEncounter == "Antenatal" || typeOfEncounter == "Neonatal" || typeOfEncounter == "Postnatal")
                        {
                            await this.appointmentsServices.UpdateEncounterTypeAsync(model.AppointmentId,
                                (int)EncounterTypes.OBEncounter, model.IsAdmission);
                        }
                        else if (typeOfEncounter == "Others")
                        {
                            await this.appointmentsServices.UpdateEncounterTypeAsync(model.AppointmentId,
                                (int)EncounterTypes.InternalMedicine, model.IsAdmission);
                        }
                    }
                    else
                    {
                        if (appointmentDetails.EncounterType == null)
                        {
                            await this.appointmentsServices.UpdateEncounterTypeAsync(model.AppointmentId,
                                                           (int)EncounterTypes.EmergencyEncounter, model.IsAdmission);
                        }

                    }
                    if (encounterId.Response > 0)
                    {
                        if (encounterId.Status == 1 && model.EmergencyEncounterId == 0)
                        {
                            await NotificationHelper.Notification(
                                basicDetails.PatientId,
                                Roles.Patient,
                                model.EmergencyEncounterId == 0
                                    ? NotificationIntimate.FullTranscriptionAdded
                                    : NotificationIntimate.FullTranscriptionUpdated,
                                this.aesHelper.Encrypt(model.AppointmentId.ToString()),
                                this.accountSessionServices,
                                this.pushNotificationHelper);
                        }

                        if (encounterId.Status == 2)
                        {
                            await NotificationHelper.Notification(
                                basicDetails.PatientId,
                                Roles.Patient,
                                model.EmergencyEncounterId == 0
                                    ? NotificationIntimate.PrescriptionAdded
                                    : NotificationIntimate.PrescriptionUpdated,
                                this.aesHelper.Encrypt(model.AppointmentId.ToString()),
                                this.accountSessionServices,
                                this.pushNotificationHelper);
                        }
                    }
                    return this.Success(encounterId.Response);
            }
        }

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

        }
        /// <summary>
        /// The find emergency encounter.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("find")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindAsync([FromBody] EmergencyEncounterFilterModel model)
        {
            model = (EmergencyEncounterFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var emergencyEncounter = await this.emergencyEncounterService.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");
                }


                if (emergencyEncounter.EmergencyEncounterId == null)
                {
                    oldAppointment = await this.appointmentsServices.FindPreviousAppointmentAsync(appointmentId);
                    if (oldAppointment != null)
                    {
                        oldAppointment.EncryptedAppointmentId =
                            this.aesHelper.Encode(oldAppointment.AppointmentId.ToString());
                    }
                }
            }

            return this.Success(new { Dashboard = emergencyEncounter, Appointments = appointmentList, OldAppointment = oldAppointment });
        }
        /// <summary>
        /// The find emergency encounter.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("find-all")]
        [ProducesResponseType(typeof(EncounterResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindAllAsync([FromBody] EmergencyEncounterFilterModel model)
        {
            var emergencyEncounter = await this.emergencyEncounterService.FindAllAsync((int)model.ProviderId);
            return this.Success(emergencyEncounter);
        }
    }

}

