namespace Hims.Api.Controllers
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain.Services;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Npgsql;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library.Enums;
    using Utilities;

    using Hims.Api.Helper;
    using Hims.Api.Models.Homeopathy;
    using Hims.Domain.Helpers;
    using Hims.Shared.Library;
    using Hims.Shared.UserModels;
    using Hims.Shared.UserModels.Filters;
    using Hims.Api.Models;

    /// <inheritdoc />
    [Authorize]
    [Route("api/homeopathy")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class HomeopathyController : 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 Homeopathy services.
        /// </summary>
        private readonly IHomeopathyService homeopathyServices;

        /// <summary>
        /// The audit log services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

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

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

        /// <inheritdoc />
        public HomeopathyController(
            IHomeopathyService homeopathyServices,
            IAuditLogService auditLogServices,
            IAESHelper aesHelper,
            IEncounterService encounterServices,
            IPushNotificationHelper pushNotificationHelper,
            IAccountSessionService accountSessionServices,
            IAppointmentService appointmentsServices)
        {
            this.homeopathyServices = homeopathyServices;
            this.auditLogServices = auditLogServices;
            this.aesHelper = aesHelper;
            this.encounterServices = encounterServices;
            this.pushNotificationHelper = pushNotificationHelper;
            this.accountSessionServices = accountSessionServices;
            this.appointmentsServices = appointmentsServices;
        }

        /// <summary>
        /// The find Behavioral health.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("find")]
        [ProducesResponseType(typeof(HomeopathyResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindAsync([FromBody] HomeopathyFilterModel model)
        {
            model = (HomeopathyFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var response = await this.homeopathyServices.FindAsync(appointmentId);
            var providerId = !string.IsNullOrEmpty(model.EncryptedProviderId) ? Convert.ToInt32(this.aesHelper.Decode(model.EncryptedProviderId)) : 0;
            var patientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));
            var appointments = await this.appointmentsServices.FindByPatientAsync(patientId, providerId);
            var 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");
            }

            var oldAppointment = new PreviousAppointmentModel();
            if (response == null || response.HomeopathyId == 0)
            {
                oldAppointment = await this.appointmentsServices.FindPreviousAppointmentAsync(appointmentId);
                if (oldAppointment != null)
                {
                    oldAppointment.EncryptedAppointmentId = this.aesHelper.Encode(oldAppointment.AppointmentId.ToString());
                }
            }

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

        /// <summary>
        /// The find Behavioral health.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("find-homeopathy")]
        [ProducesResponseType(typeof(HomeopathyResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindHomeopathyAsync([FromBody] HomeopathyFilterModel model)
        {
            model = (HomeopathyFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var homeopathy = await this.homeopathyServices.FindAsync(appointmentId);

            return this.Success(homeopathy);
        }

        /// <summary>
        /// To find Behavioral health dashboard
        /// </summary>
        /// <param name="model" >
        /// The behavioral health filter model.
        /// </param>
        /// <returns>
        /// The behavioral model.
        /// </returns>
        [HttpPost]
        [Route("find-dashboard")]
        [ProducesResponseType(typeof(HomeopathyResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindDashboardAsync([FromBody] HomeopathyFilterModel model)
        {
            model = (HomeopathyFilterModel)EmptyFilter.Handler(model);

            if (!string.IsNullOrEmpty(model.EncryptedAppointmentId) && model.EncryptedAppointmentId.EndsWith("%3D"))
            {
                model.EncryptedAppointmentId = model.EncryptedAppointmentId.Replace("%3D", "=");
            }

            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));

            var response = await this.homeopathyServices.FetchAsync(appointmentId, model.Type);
            return this.Success(response);
        }

        /// <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] HomeopathyEncounterModifyModel model)
        {
            model = (HomeopathyEncounterModifyModel)EmptyFilter.Handler(model);
            var encounterId = model.HomeopathyId == 0 
                                  ? await this.homeopathyServices.AddAltAsync(model) 
                                  : await this.homeopathyServices.UpdateAltAsync(model);
            switch (encounterId.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.Homeopathy, model.IsAdmission);

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

        /// <summary>
        /// The delete Homeopathy.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Homeopathy deleted successfully.
        /// - 409 - Homeopathy can not be deleted.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpDelete]
        [Route("delete")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteAsync([FromBody] HomeopathyDeleteRequestModel model,[FromHeader]LocationHeader header)
        {
            try
            {
                model = (HomeopathyDeleteRequestModel)EmptyFilter.Handler(model);
                var response = await this.homeopathyServices.DeleteAsync(model.HomeopathyId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.AccountId,
                    LogTypeId = (int)LogTypes.Countries,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow,
                    LogDescription = $"{model.HomeopathyId} Homeopathy has been deleted.",
                    LocationId= Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success("Homeopathy has been deleted successfully.");
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Conflict("Homeopathy can't be deleted. Please contact administrator.");
                }

                return this.ServerError();
            }
        }

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

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