using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Serilog;
using System.Globalization;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Web.Services.Interfaces;

namespace WorkFlowCheck.Web.Pages.CheckList.CheckListHeader
{
    public class CheckListHeaderEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly ICheckListService _checkListService;

        [BindProperty]
        public CheckListHeaderDTO CheckListHeaderDTO { get; set; }

        [BindProperty]
        public CheckListHeaderInfoDTO CheckListHeaderInfoDTO { get; set; }

        [BindProperty]
        public List<SelectListItem> CheckStatus { get; set; }

        public CheckListHeaderEditPageModel(ILogger<IndexModel> logger, ICheckListService checkListService)
        {
            _logger = logger;
            _checkListService = checkListService;
        }
        public async Task OnGet(int id)
        {
            CheckListHeaderDTO = await _checkListService.GetCheckListHeader(id);
            CheckStatus = _checkListService.GetCheckStatus();
            BuildCheckListHeaderInfo();
        }
        public async Task<IActionResult> OnPostSave([FromBody] CheckListHeaderDTO checkListHeaderDTO)
        {
            try
            {
                var result = await _checkListService.UpdateCheckListHeader(checkListHeaderDTO);
                if (result.IsSuccess)
                {
                    return new JsonResult(new { success = true });
                }
                else
                {
                    return new JsonResult(new { success = false });
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

            return new JsonResult(new { success = false });
        }
        private void BuildCheckListHeaderInfo()
        {
            CheckListHeaderInfoDTO = new CheckListHeaderInfoDTO();

            var result = CheckListHeaderDTO.CheckListRowDTO
                                            .GroupBy(r => 1)
                                            .Select(g => new
                                            {
                                                TotalRowCount = g.Count(),
                                                EmptyAnswerCount = g.Count(r => string.IsNullOrEmpty(r.Answer)),
                                                CheckPointCount = g.Select(r => r.CheckListTemplateRowDTO.CheckPointId).Distinct().Count()
                                            })
                                            .FirstOrDefault();
            if (result != null)
            {
                CheckListHeaderInfoDTO.TotalRowCount = result.TotalRowCount;
                CheckListHeaderInfoDTO.CheckPointCount = result.CheckPointCount;
                CheckListHeaderInfoDTO.EmptyAnswerCount = result.EmptyAnswerCount;
                if (CheckListHeaderInfoDTO.TotalRowCount > 0)
                {
                    CheckListHeaderInfoDTO.ReadyPercent = ((double)(CheckListHeaderInfoDTO.TotalRowCount - CheckListHeaderInfoDTO.EmptyAnswerCount) / CheckListHeaderInfoDTO.TotalRowCount * 100)
                                                               .ToString("0.00", new CultureInfo("hu-HU")) + " %"; ;
                }
            }
        }
        public async Task<JsonResult> OnGetLoadCheckListRows(int id)
        {
            CheckListHeaderDTO = await _checkListService.GetCheckListHeader(id);
            if (CheckListHeaderDTO.CheckListRowDTO?.Count() > 0)
            {
                foreach (var item in CheckListHeaderDTO.CheckListRowDTO)
                {
                    if (item.CheckListTemplateRowDTO?.AnswerType == "P")
                    {
                        if (item.Photo != null && item.Photo.Length > 0)
                        {
                            item.Answer = ConvertToBase64(item.Photo);
                        }
                    }
                }
            }

            return new JsonResult(new
            {
                data = CheckListHeaderDTO.CheckListRowDTO
            });
        }
        public string ConvertToBase64(byte[] photo)
        {
            if (photo == null || photo.Length == 0)
                return string.Empty;

            return "data:image/jpeg;base64," + Convert.ToBase64String(photo);
        }
    }
}
