namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain.Services;
    using Hims.Api.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.CodeAnalysis.CSharp;
    using Npgsql;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library.Enums;
    using Shared.UserModels.Filters;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/discharges")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class DischargeInstructionsController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IDischargeInstructionService dischargeInstructionService;

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

        /// <inheritdoc />
        public DischargeInstructionsController(IDischargeInstructionService dischargeInstructionService, IAuditLogService auditLogServices)
        {
            this.dischargeInstructionService = dischargeInstructionService;
            this.auditLogServices = auditLogServices;
        }

        /// <summary>
        /// The fetch coupons.
        /// </summary>
        /// <param name="model">
        /// The coupon filter model.
        /// </param>
        /// <returns>
        /// The list of coupons.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of coupons.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<DischargeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] DischargeFilterModel model)
        {
            model = (DischargeFilterModel)EmptyFilter.Handler(model);
            var coupons = await this.dischargeInstructionService.FetchAsync(model);
            return coupons == null ? this.ServerError() : this.Success(coupons);
        }

        /// <summary>
        /// The add coupon.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Coupon added successfully.
        /// - 409 - Coupon already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("add")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> AddAsync([FromBody]DischargeModel model, [FromHeader] LocationHeader header)
        {
            model = (DischargeModel)EmptyFilter.Handler(model);
            var response = await this.dischargeInstructionService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given discharge instructions already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.DischargeInstructions,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" <b>{model.ModifiedByName}</b> has added Discharge Instructions <b>{model.DischargeInstructionName}</b> on {DateTime.UtcNow.AddMinutes(330)}",
                LocationId=Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Discharge Instruction has been added successfully.");
        }

        /// <summary>
        /// The update coupon.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Coupon updated successfully.
        /// - 409 - Coupon already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPut]
        [Route("update")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateAsync([FromBody] DischargeModel model, [FromHeader] LocationHeader header)
        {
            model = (DischargeModel)EmptyFilter.Handler(model);
            var response = await this.dischargeInstructionService.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Discharge Instruction has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.DischargeInstructions,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" <b>{model.ModifiedByName}</b> has updated Discharge Instructions <b>{model.DischargeInstructionName}</b> on {DateTime.UtcNow.AddMinutes(330)}",
                LocationId= Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Discharge Instruction has been updated successfully.");
        }

        

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

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

                return this.ServerError();
            }
        }

        /// <summary>
        /// Modifies the ware house status asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("modify-status")]
        public async Task<ActionResult> ModifyStatus([FromBody] DischargeModel model, [FromHeader] LocationHeader header)
        {
            model = (DischargeModel)EmptyFilter.Handler(model);
            var response = await this.dischargeInstructionService.ModifyStatusAsync(model);
            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.DischargeInstructions,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" <b>{model.ModifiedByName}</b> has {((bool)model.Active ? "Activated" : "Deactivated")} Discharge Instructions <b>{model.DischargeInstructionName}</b> on {DateTime.UtcNow.AddMinutes(330)}",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success(response);
        }


    }
}