namespace Hims.Api.Controllers
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain.Helpers;
    using Domain.Services;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    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.Helper;

    /// <summary>
    /// The behavioral controller.
    /// </summary>
    [Authorize]
    [Route("api/behavioral-health")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class BehavioralHealthController : 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 provider service
        /// </summary>
        private readonly IBehavioralHealthService behavioralHealthServices;

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

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

        /// <inheritdoc />
        public BehavioralHealthController(
            IBehavioralHealthService behavioralHealthServices,
            IAppointmentService appointmentsServices,
            IEncounterService encounterServices,
            IPushNotificationHelper pushNotificationHelper,
            IAccountSessionService accountSessionServices,
            IAESHelper aesHelper)
        {
            this.behavioralHealthServices = behavioralHealthServices;
            this.appointmentsServices = appointmentsServices;
            this.aesHelper = aesHelper;
            this.encounterServices = encounterServices;
            this.pushNotificationHelper = pushNotificationHelper;
            this.accountSessionServices = accountSessionServices;
        }

        /// <summary>
        /// The find Behavioral health.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("find")]
        [ProducesResponseType(typeof(BehavioralHealthModel), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindAsync([FromBody] BehavioralFilterModel model)
        {
            model = (BehavioralFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var response = await this.behavioralHealthServices.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.BehavioralHealthId == 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-behavioral-health")]
        [ProducesResponseType(typeof(BehavioralHealthModel), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindBehavioralHealthAsync([FromBody] BehavioralFilterModel model)
        {
            model = (BehavioralFilterModel)EmptyFilter.Handler(model);

            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var behavioralHealth = await this.behavioralHealthServices.FindAsync(appointmentId);
            return this.Success(behavioralHealth);
        }

        /// <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(BehavioralHealthResource), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindDashboardAsync([FromBody] BehavioralFilterModel model)
        {
            model = (BehavioralFilterModel)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.behavioralHealthServices.FindDashboardAsync(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(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyAsync([FromBody] BehavioralModifyModel model)
        {
            model = (BehavioralModifyModel)EmptyFilter.Handler(model);
            var response = await this.behavioralHealthServices.UpdateAltAsync(model);
            switch (response.Response)
            {
                case -1:
                    return this.Conflict("Behavioral Health has been exist with the selected appointment.");
                case 0:
                    return this.ServerError();
                default:
                    var basicDetails = await this.encounterServices.GetBasicAppointmentDetails(model.AppointmentId, model.IsAdmission);
                    await this.appointmentsServices.UpdateEncounterTypeAsync(model.AppointmentId, (int)EncounterTypes.BehavioralHealth, model.IsAdmission);

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

                    if (response.Status == 2)
                    {
                        await NotificationHelper.Notification(
                            basicDetails.PatientId,
                            Roles.Patient,
                            NotificationIntimate.PrescriptionAdded,
                            this.aesHelper.Encrypt(model.AppointmentId.ToString()),
                            this.accountSessionServices,
                            this.pushNotificationHelper);
                    }

                    return this.Success(response.Response);
            }
        }

        /// <summary>
        /// The find prescription async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("find-prescription")]
        [ProducesResponseType(typeof(BehavioralPrescriptionModel), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindPrescriptionAsync([FromBody] BehavioralFilterModel model)
        {
            model = (BehavioralFilterModel)EmptyFilter.Handler(model);
            var appointmentId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedAppointmentId));
            var behavioralPrescription = await this.behavioralHealthServices.FindPrescriptionAsync(appointmentId);
            if (behavioralPrescription == null || behavioralPrescription.BehavioralHealthId == 0)
            {
                return this.BadRequest("Sorry! We don't have a it in the system.");
            }

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

        /// <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(InternalMedicineFullTranscriptModel), 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.behavioralHealthServices.FindFullTranscriptAsync(appointmentId);
            if (fullTranscript == null || fullTranscript.BehavioralHealthId == 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);
        }
    }
}