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

namespace WorkFlowCheck.Web.Pages.CheckListTemplate.CheckListTemplateHeader
{
    public class CheckListTemplateHeaderEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly ICheckListService _checkListService;
        private readonly IBaseStockService _baseStockService;

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

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

        public CheckListTemplateHeaderEditPageModel(ILogger<IndexModel> logger, ICheckListService checkListService, IBaseStockService baseStockService)
        {
            _logger = logger;
            _checkListService = checkListService;
            _baseStockService = baseStockService;
        }
        public async Task OnGet(int id)
        {
            await InitSelectItems();
            CheckListTemplateHeaderDTO = await _checkListService.GetCheckListTemplateHeader(id);
        }
        public async Task<JsonResult> OnGetLoadCheckListTemplateRows(int id)
        {
            CheckListTemplateHeaderDTO = await _checkListService.GetCheckListTemplateHeader(id);
            return new JsonResult(new { data = CheckListTemplateHeaderDTO.CheckListTemplateRowDTO });
        }
        public async Task<IActionResult> OnPostSave([FromBody] CheckListTemplateHeaderDTO checkListTemplateHeaderDTO)
        {
            try
            {
                var result = await _checkListService.UpdateCheckListTemplateHeader(checkListTemplateHeaderDTO);
                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 async Task InitSelectItems()
        {
            var numbergenerators = await _baseStockService.GetNumbergenerators();

            this.Numbergenerators = new List<SelectListItem>();
            foreach (var numbergenerator in numbergenerators)
            {
                this.Numbergenerators.Add(new SelectListItem()
                {
                    Value = numbergenerator.Id.ToString(),
                    Text = $"{numbergenerator.ShortName} -> [{numbergenerator.Sample}]"
                });
            }
        }
    }
}
