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 RoleCheckPointEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IUserService _userService;
        private readonly IBaseStockService _baseStockService;

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

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

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

        public RoleCheckPointEditPageModel(ILogger<IndexModel> logger, IUserService userService, IBaseStockService baseStockService)
        {
            _logger = logger;
            _userService = userService;
            _baseStockService = baseStockService;
        }

        public async Task OnGet(int id)
        {
            await InitSelectItems();
            RoleCheckPointDTO = await _userService.GetRoleCheckPoint(id);
        }
        public async Task<IActionResult> OnPostSave([FromBody] RoleCheckPointDTO roleCheckPointDTO)
        {
            try
            {
                var result = await _userService.UpdateRoleCheckPoint(roleCheckPointDTO);
                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 CheckPoints = await _baseStockService.GetAllCheckPoints();
            this.RoleCheckPoints = new List<SelectListItem>();
            foreach (var CheckPoint in CheckPoints)
            {
                this.RoleCheckPoints.Add(new SelectListItem() { Value = CheckPoint.Id.ToString(), Text = CheckPoint.ShortName });
            }
        }
    }
}
