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.UserAndRole
{
    public class RoleCheckListTemplateHeaderEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IUserService _userService;
        private readonly ICheckListService _checkListService;

        [BindProperty]
        public RoleCheckListTemplateHeaderDTO RoleCheckListTemplateHeaderDTO { get; set; } = new();

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

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

        public RoleCheckListTemplateHeaderEditPageModel(ILogger<IndexModel> logger, IUserService userService, ICheckListService checkListService)
        {
            _logger = logger;
            _userService = userService;
            _checkListService = checkListService;
        }

        public async Task OnGet(int id)
        {
            await InitSelectItems();
            RoleCheckListTemplateHeaderDTO = await _userService.GetRoleCheckListTemplateHeader(id);
        }
        public async Task<IActionResult> OnPostSave([FromBody] RoleCheckListTemplateHeaderDTO roleCheckListTemplateHeaderDTO)
        {
            try
            {
                var result = await _userService.UpdateRoleCheckListTemplateHeader(roleCheckListTemplateHeaderDTO);
                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 roles = await _userService.GetAllRoles();
            this.Roles = new List<SelectListItem>();
            foreach (var role in roles)
            {
                this.Roles.Add(new SelectListItem() { Value = role.Id.ToString(), Text = role.RoleName });
            }
            var checkListTemplateHeaders = await _checkListService.GetAllCheckListTemplateHeaderAsync();
            this.RoleCheckListTemplateHeaders = new List<SelectListItem>();
            foreach (var checkListTemplateHeader in checkListTemplateHeaders)
            {
                this.RoleCheckListTemplateHeaders.Add(new SelectListItem() { Value = checkListTemplateHeader.Id.ToString(), Text = checkListTemplateHeader.ShortName });
            }
        }
    }
}
