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/beds")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class BedController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IBedService bedService;

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

        /// <inheritdoc />
        public BedController(IBedService bedService, IAuditLogService auditLogServices)
        {
            this.bedService = bedService;
            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]
        [Authorize]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<BedModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] BedFilterModel model,[FromHeader] LocationHeader header)
        {
            model = (BedFilterModel)EmptyFilter.Handler(model);
            model.LocationId = model.LocationId > 0 ? model.LocationId : null;
            var beds = await this.bedService.FetchAsync(model);
            return beds == null ? this.ServerError() : this.Success(beds);
        }


        /// <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] BedModel model, [FromHeader] LocationHeader header)
        {
            model = (BedModel)EmptyFilter.Handler(model);
            var response = await this.bedService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Bed has already been exists with us.");
                case -2:
                    return this.Conflict("Max Beds are Already Filled in this Room, Please Increase the Room count for Selected Room.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.Bed,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" {model.ModifiedByName} has Added Bed - {model.BedNumber} on { DateTime.UtcNow.AddMinutes(330) }",
                LocationId=Convert.ToInt32( header.LocationId)

            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Bed 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] BedModel model, [FromHeader] LocationHeader header)
        {
            model = (BedModel)EmptyFilter.Handler(model);
            var response = await this.bedService.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given bed has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Bed,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" {model.ModifiedByName} has Updated Bed - {model.BedNumber} on { DateTime.UtcNow.AddMinutes(330) }",
                LocationId=Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Bed 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] BedModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (BedModel)EmptyFilter.Handler(model);
                //var bedId = await this.bedService.FindNumberByBedId(model.BedId);
                var response = await this.bedService.DeleteAsync(model.BedId);
                switch (response)
                {
                    case -1:
                        return this.Conflict("Unable to Find Bed");
                    case -2:
                        return this.Conflict("Bed is allocated, please Deallocate then try");
                    case 0:
                        return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Bed,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $" {model.ModifiedByName} has Deleted Bed - {model.BedNumber} on { DateTime.UtcNow.AddMinutes(330) }",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success("Bed 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 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("fetchBed")]
        [ProducesResponseType(typeof(List<BedModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchRoomAsync([FromBody] BedFilterModel model)
        {
            model = (BedFilterModel)EmptyFilter.Handler(model);
            var wards = await this.bedService.FetchBedAsync(model);
            return wards == null ? this.ServerError() : this.Success(wards);
        }

        /// <summary>
        /// Changes the status asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="header">The header.</param>
        /// <returns></returns>
        [HttpPut]
        [Route("change-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ChangeStatusAsync([FromBody] BedModel model, [FromHeader] LocationHeader header)
        {
            model = (BedModel)EmptyFilter.Handler(model);
            var response = await this.bedService.ChangeStatusAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Unable to Find Bed");
                case -2:
                    return this.Conflict("Bed is allocated, please Deallocate then try");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Bed,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" {model.ModifiedByName} has changed status of  Bed - {model.BedNumber}  to {(model.Active ? "Active" :"Deactivate")  } on { DateTime.UtcNow.AddMinutes(330) }",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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