using Microsoft.AspNetCore.Authorization;
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.BaseStock.CheckPoints
{
    [Authorize]
    [ValidateAntiForgeryToken]
    public class CheckPointEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IBaseStockService _baseStockService;
        private readonly IUserService _userService; 

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

        public CheckPointEditPageModel(ILogger<IndexModel> logger, 
                                       IBaseStockService baseStockService,
                                       IUserService userService)
        {
            _baseStockService = baseStockService;
            _userService = userService;
            _logger = logger;
        }
        public async Task OnGet(int id)
        {
            await InitSelectItems();
            CheckPointDTO = await _baseStockService.GetCheckPoint(id);

        }
        public async Task<JsonResult> OnGetLoadCheckListTemplateRows(int id)
        {
            CheckPointDTO = await _baseStockService.GetCheckPoint(id);
            return new JsonResult(new { data = CheckPointDTO.CheckListTemplateRowDTO });
        }

        public async Task<IActionResult> OnPostSave([FromBody] CheckPointDTO checkPointDTO)
        {
            try
            {
                var result = await _baseStockService.UpdateCheckPoint(checkPointDTO);
                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();
            Roles = new List<SelectListItem>();
            Roles.Add(new SelectListItem() { Value = "-1", Text = "NINCS" });
            foreach (var role in roles)
            {
                Roles.Add(new SelectListItem() { Value = role.Id.ToString(), Text = role.RoleName });
            }
        }
    }
}
