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

    /// <inheritdoc />
    [Authorize]
    [Route("api/specializations")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class SpecializationsController : BaseController
    {
        /// <summary>
        /// The specialization services.
        /// </summary>
        private readonly ISpecializationService specializationsServices;

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

        /// <inheritdoc />
        public SpecializationsController(ISpecializationService specializationsServices, IAuditLogService auditLogServices)
        {
            this.specializationsServices = specializationsServices;
            this.auditLogServices = auditLogServices;
        }

        /// <summary>
        /// The fetch specializations.
        /// </summary>
        /// <param name="model">
        /// The specialization filter model.
        /// </param>
        /// <returns>
        /// The list of specializations.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of specializations.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<SpecializationModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody]SpecializationFilterModel model)
        {
            model = (SpecializationFilterModel)EmptyFilter.Handler(model);
            var specializations = await this.specializationsServices.FetchAsync(model);
            foreach (var item in specializations)
            {
                if (item.Url != null)
                {
                    var substring = item.Url.Substring(0, 9);
                    if (substring == "vs/Icons/")
                    {
                        item.Url = item.Url.Substring(9);
                    }
                }
            }
            return specializations == null ? this.ServerError() : this.Success(specializations);
        }

        /// <summary>
        /// The add specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Specialization added successfully.
        /// - 409 - Specialization 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]SpecializationModel model,[FromHeader] LocationHeader header)
        {
            model = (SpecializationModel)EmptyFilter.Handler(model);
            var response = await this.specializationsServices.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given specialization name has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.Specializations,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.Now,
                LogDescription = $"<b>{model.CreatedByName}<b> <b>has added Specialization</b> of <strong>{model.SpecializationName}</strong> successfully.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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

        /// <summary>
        /// The update specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Specialization updated successfully.
        /// - 409 - Specialization 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]SpecializationModel model, [FromHeader] LocationHeader header)
        {
            model = (SpecializationModel)EmptyFilter.Handler(model);
            var response = await this.specializationsServices.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given specialization name has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Specializations,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.Now,
                LogDescription = $"<b>{model.ModifiedByName}<b> <b>has updated Specialization</b> of <strong>{model.SpecializationName}</strong> successfully.",
              
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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

        /// <summary>
        /// The delete specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Specialization deleted successfully.
        /// - 409 - Specialization 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]SpecializationModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (SpecializationModel)EmptyFilter.Handler(model);
                var response = await this.specializationsServices.DeleteAsync(model.SpecializationId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Specializations,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.Now,
                    LogDescription = $"<b>{model.ModifiedByName}<b> <b>has deleted Specialization</b> of <strong>{model.SpecializationName}</strong> successfully.",
                 
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

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

                return this.ServerError();
            }
        }

        /// <summary>
        /// The modify status of specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Specialization status updated successfully.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPut]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody]SpecializationModel model,[FromHeader] LocationHeader header)
        {
            model = (SpecializationModel)EmptyFilter.Handler(model);
            var response = await this.specializationsServices.ModifyStatusAsync(model.SpecializationId, Convert.ToInt32(model.ModifiedBy), model.Active);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.Specializations,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.Now,
                LogDescription = $@"<b>{model.CreatedByName}</b> has {((bool)model.Active ? "Deactivated" : "Activated")} the SpecializationName <b> {model.SpecializationName}</b>  successfully",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Specialization status has been updated successfully.");
        }

        /// <summary>
        /// Fetches the specialization join consultation type asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("specialization-join-consultation")]
        [ProducesResponseType(typeof(List<SpecializationModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchSpecializationJoinConsultationTypeAsync([FromBody] SpecializationFilterModel model)
        {
            model = (SpecializationFilterModel)EmptyFilter.Handler(model);
            var specializations = await this.specializationsServices.FetchSpecializationJoinConsultationTypeAsync(model);
            foreach (var item in specializations)
            {
                if (item.Url != null)
                {
                    var substring = item.Url.Substring(0, 9);
                    if (substring == "vs/Icons/")
                    {
                        item.Url = item.Url.Substring(9);
                    }
                }
            }
            return specializations == null ? this.ServerError() : this.Success(specializations);
        }
    }
}