using DocumentFormat.OpenXml.Math;
using Hims.Api.Models;
using Hims.Api.Utilities;
using Hims.Domain.Services;
using Hims.Shared.DataFilters;
using Hims.Shared.EntityModels;
using Hims.Shared.Library.Enums;
using Hims.Shared.UserModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using Hims.Domain.Helpers;
using System.Threading.Tasks;

namespace Hims.Api.Controllers
{
    /// <inheritdoc />
    [Authorize]
    [Route("api/template-config")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class DynamicTemplateConfigController : BaseController
    {
        /// <summary>
        /// The dynamic template config services.
        /// </summary>
        private readonly IDynamicTemplateConfigService dynamicTemplateConfigService;
        /// <summary>
        /// The audit log services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

        private readonly IAESHelper aesHelper;

        /// <inheritdoc />
        public DynamicTemplateConfigController(
            IAESHelper aesHelper,
            IDynamicTemplateConfigService dynamicTemplateConfigService, IAuditLogService auditLogService)
        {
            this.dynamicTemplateConfigService = dynamicTemplateConfigService;
            this.auditLogServices = auditLogService;
            this.aesHelper = aesHelper;
        }

        /// <summary>
        /// Inserts the hoc asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="location">The location.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("add")]
        public async Task<ActionResult> InsertAsync([FromBody] DynamicTemplateConfigModel model, [FromHeader] LocationHeader header)
        {
            model = (DynamicTemplateConfigModel)EmptyFilter.Handler(model);
            var response = await this.dynamicTemplateConfigService.InsertAsync(model);
            try
            {
                if (response > 0)
                {
                    var auditLog = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.DynamicTemplateConfig,
                        LogDate = DateTime.Now,
                        LogFrom = (short)model.LoginRoleId,
                        LogDescription = $"{model.CreatedByName} has added <b>Dynamic template</b> of <strong>{model.ReportName}</strong> successfully.",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLog);
                }
            }
            catch (Exception ex)
            {
                //ignore
            }
            return this.Success(response);
        }

        /// <summary>
        /// Fetches all asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch-all")]
        public async Task<ActionResult> FetchAsync([FromBody] DynamicTemplateConfigModel model)
        {
            model = (DynamicTemplateConfigModel)EmptyFilter.Handler(model);
            var response = await this.dynamicTemplateConfigService.FetchAllAsync(model);
            return this.Success(response);
        }

        /// <summary>
        /// Fetches all asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch-report-configs")]
        public async Task<ActionResult> FetchReportConfigsAsync([FromBody] GetTemplateConfigs model)
        {
            model = (GetTemplateConfigs)EmptyFilter.Handler(model);
            var response = await this.dynamicTemplateConfigService.FetchTemplateConfigs(model);
            foreach (var item in response)
            {
                item.EncryptedId = this.aesHelper.Encode(item.Id.ToString());
            }
            return this.Success(response);
        }


        /// <summary>
        /// Fetches all asynchronous.
        /// </summary>
        [HttpPost]
        [Route("fetch-dynamic-reports")]
        public async Task<ActionResult> FetchAsync()
        {

            var response = await this.dynamicTemplateConfigService.FetchDynamicTemplate();
            return this.Success(response);
        }


        [HttpPost]
        [Route("update")]
        public async Task<ActionResult> UpdateAsync([FromBody] DynamicTemplateConfigModel model, [FromHeader] LocationHeader header)
        {
            model = (DynamicTemplateConfigModel)EmptyFilter.Handler(model);
            var response = await this.dynamicTemplateConfigService.UpdateAsync(model);
            try
            {
                if (response > 0)
                {
                    var auditLog = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.DynamicTemplateConfig,
                        LogDate = DateTime.Now,
                        LogFrom = short.Parse(model.LoginRoleId.ToString()),
                        LogDescription = $"{model.CreatedByName} has updated <b>Dynamic Template</b> of <strong>{model.ReportName}</strong> successfully.",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLog);
                }
            }
            catch (Exception ex)
            {
                //ignore
            }
            return this.Success(response);
        }


        [HttpPost]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] DynamicTemplateConfigModel model, [FromHeader] LocationHeader header)
        {
            model = (DynamicTemplateConfigModel)EmptyFilter.Handler(model);
            var response = await this.dynamicTemplateConfigService.ActivateOrDeactivateTest(model);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.DynamicTemplateConfig,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $@"<b>{model.ModifiedByName}</b> has {((bool)model.Active ? "Activated" : "Deactivated")} the {model.ReportName}  successfully",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success(response);

        }
    }
}
