using Hims.Shared.UserModels.Common;
namespace Hims.Api.Controllers
{

    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Hims.Api.Utilities;
    using Hims.Domain.Services;
    using Hims.Shared.EntityModels;
    using System;
    using Hims.Domain.Helpers;
    using Hims.Domain.Repositories.UnitOfWork;
    using DocumentFormat.OpenXml.Presentation;
    using Hims.Domain.Configurations;
    using DocumentFormat.OpenXml.Vml;
    using System.Collections.Generic;

    /// <inheritdoc />
    [Authorize]
    [Route("api/dynamic-report")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class DynamicReportController : BaseController
    {
        /// <summary>
        /// The resource services.
        /// </summary>
        private readonly IDynamicReportService dynamicReportServices;

        /// <summary>
        /// The AES helper.
        /// </summary>
        private readonly IAESHelper aesHelper;
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;
        /// <summary>
        /// The running environment.
        /// </summary>
        private readonly IRunningEnvironment runningEnvironment;
        /// <summary>
        /// The FTP upload helper.
        /// </summary>
        private readonly IFtpUploadHelper ftpUploadHelper;

        /// <inheritdoc />
        public DynamicReportController(IDynamicReportService dynamicReportService, IAESHelper aesHelper, IUnitOfWork unitOfWork, IRunningEnvironment runningEnvironment, IFtpUploadHelper ftpUploadHelper)
        {
            this.dynamicReportServices = dynamicReportService;
            this.aesHelper = aesHelper;
            this.unitOfWork = unitOfWork;
            this.runningEnvironment = runningEnvironment;
            this.ftpUploadHelper = ftpUploadHelper;
        }



        ///// <summary>
        ///// To Execute the Query only.
        ///// </summary>
        ///// <param name="model">
        ///// The model
        ///// </param>
        ///// <returns>
        ///// The <see cref="Task"/>.
        ///// </returns>
        ///// <remarks>
        ///// ### REMARKS ###
        ///// The following codes are returned
        ///// -xxx - Returns the Success for Query (Executed)
        ///// -xxx - Returns the Error for Query (Not-Executed)
        ///// </remarks>
        //[HttpPost]
        //[Route("execute-the-query")]
        //public async Task<ActionResult> ExecuteQuery([FromBody] DynamicReportModel model)
        //{
        //    try
        //    {
        //        var res = await this.dynamicReportServices.ExecuteQueryAsync(model);

        //        return Ok(new GenericResponse
        //        {
        //            Status = GenericStatus.Success,
        //            Data = res
        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        return Ok(new GenericResponse
        //        {
        //            Status = GenericStatus.Error,
        //            Message = ex.Message
        //        });
        //    }
        //}

       /// <summary>
       ///  to save/insert the Record
       /// </summary>
       /// <param name="model">
       /// The model
       /// </param>
       /// <returns>
       /// The <see cref="Task"/>.
       /// </returns>
        [HttpPost]
        [Route("insert")]
        public async Task<ActionResult> InsertAsync([FromBody] DynamicReportModel model)
        {
            try
            {
                var response = await this.dynamicReportServices.InsertAsync(model);

                return Ok(new GenericResponse
                {
                    Status = response switch
                    {
                        -1 => GenericStatus.Error,
                        -2 => GenericStatus.Info,
                        _=> GenericStatus.Success
                    },
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The fetch .
        /// </summary>
        /// <param name="model">
        /// The widget filter model.
        /// </param>
        /// <returns></returns>
        // All list of Record Query which is Saved
        [Authorize]
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchAsync([FromBody] DynamicReportFilterModel model)
        {
            try
            {
                var response = await this.dynamicReportServices.FetchAsync(model);
                foreach (var item in response)
                {
                    item.EncryptedDynamicReportId = this.aesHelper.Encode(item.DynamicReportId.ToString());
                }
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The deactivate  async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("deactivate")]
        public async Task<ActionResult> DeactivateAsync([FromBody] DynamicReportModel model)
        {
            try
            {
                var response = await this.dynamicReportServices.DeactivateAsync(model.DynamicReportId, model.ModifiedBy);



                return Ok(new GenericResponse
                {
                    Status = response switch
                    {
                        -1 => GenericStatus.Error,
                        -2 => GenericStatus.Info,
                        _ => GenericStatus.Success
                    },
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        ///  to Update the Record/Query
        /// </summary>
        /// <param name="model">
        /// The model
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        
        [HttpPost]
        [Route("update")]
        public async Task<ActionResult> Update([FromBody] DynamicReportModel model)
        {
            try
            {
                model.DynamicReportId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedDynamicReportId));
                var response = await this.dynamicReportServices.UpdateAsync(model);

                return Ok(new GenericResponse
                {
                    Status = response switch
                    {
                        -1 => GenericStatus.Error,
                        -2 => GenericStatus.Info,
                        _ => GenericStatus.Success
                    },
                    Data = response
                });
            }
            catch(Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });

            }
        }

        /// <summary>
        ///  to Fetch verified Reports 
        /// </summary>
        [HttpGet]
        [Route("fetch-report-menu")]
        public async Task<ActionResult> GetReportMenu()
        {
            try
            {
                var list = await this.dynamicReportServices.GetReportMenuAsync();
                return Success(list);
            }
            catch(Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// Inserts the template asynchronous.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("fetch-module-templates")]
        public async Task<ActionResult> FetchModuleTemplatesAsync()
        {
            var response = await this.dynamicReportServices.FetchModuleTemplatesAsync();
            return this.Success(response);
        }

        /// <summary>
        /// The fetch .
        /// </summary>
        /// <returns>        
        /// <returns></returns>
        // All list of Record Query which is Saved
        [Authorize]
        [HttpGet]
        [Route("fetch-report")]
        public async Task<ActionResult> FetchReportAsync(string encryptedReportId)
        {
            try
            {
                var reportId = Convert.ToInt32(this.aesHelper.Decode(encryptedReportId));
                var response = await this.dynamicReportServices.FetchReportAsync(reportId);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        ///  to save/insert the Record
        /// </summary>
        /// <param name="model">
        /// The model
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [Route("insert-image")]
        public async Task<ActionResult> InsertImageAsync([FromBody] DynamicReportImagesModel model)
        {
            
                var response = await this.dynamicReportServices.InsertImages(model);
                var inserted = await this.unitOfWork.DynamicReportImages.FindAsync(s => s.DynamicReportImagesId == response);
            
                var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/DynamicReportImages/{inserted.Guid}";

                try
                {
                    await this.ftpUploadHelper.CreateDirectory(filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                var dbPath = $@"{inserted.DynamicReportImagesId}_{DateTime.UtcNow.Ticks}.jpg";
                filePath += $@"/{dbPath}";

                try
                {
                    var uploadResponse = await this.ftpUploadHelper.UploadProfileImageAsync(model.Base64Image, filePath);
                    if (uploadResponse > 0)
                    {
                        model.ImagePath = $@"{filePath}";
                        
                    }
                }
                catch (Exception)
                {
                    model.ImagePath = null;
                   
                }
                var final = await this.dynamicReportServices.UpdateImages(model.ImagePath, inserted.DynamicReportImagesId);


            return this.Success(model.ImagePath);
 
           
        }


        /// <summary>
        /// The fetch .
        /// </summary>
        /// <returns>        
        /// <returns></returns>
        // All list of Record Query which is Saved
        [Authorize]
        [HttpGet]
        [Route("fetch-image-path")]
        public async Task<IEnumerable<DynamicReportImagesModel>> FetchImagePath()
        {
            var res = await this.dynamicReportServices.FetchImagePath();
            return res;
        }


    }
}
