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

namespace WorkFlowCheck.Web.Pages.UserAndRole
{
    public class UserRoleEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IUserService _userService;

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

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

        public async Task OnGet(int id)
        {
            await InitSelectItems();   
            UserRoleDTO = await _userService.GetUserRole(id);
        }
        public async Task<IActionResult> OnPostSave([FromBody] UserRoleDTO userRoleDTO)
        {
            try
            {
                var result = await _userService.UpdateUserRole(userRoleDTO);
                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 users = await _userService.GetAllUsers();
            this.Users = new List<SelectListItem>();
            foreach (var user in users)
            {
                this.Users.Add(new SelectListItem() { Value = user.Id.ToString(), Text = user.UserName });
            }
        }
    }
}
