using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
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; }
        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();
        }
        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);
        }
    }
}
