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

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

        public RoleEditPageModel(ILogger<IndexModel> logger, IUserService userService)
        {
            _userService = userService;
            _logger = logger;
        }

        public async Task OnGet(int id)
        {
            await InitSelectItems();
            RoleDTO = await _userService.GetRole(id);
        }
        public async Task<IActionResult> OnPostSave([FromBody] RoleDTO roleDTO)
        {
            try
            {
                var result = await _userService.UpdateRole(roleDTO);
                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.Parents = new List<SelectListItem>();
            Parents.Add(new SelectListItem() { Value = "-1", Text = "NINCS" });
            foreach (var role in roles)
            {
                Parents.Add(new SelectListItem() { Value = role.Id.ToString(), Text = role.RoleName });
            }
        }
    }
}
