using System.Diagnostics;
using bitforum.Models;
using bitforum.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using bitforum.Helpers;
using bitforum.Models.User;
using Microsoft.AspNetCore.Identity;

namespace bitforum.Controllers.Setting
{
    [Authorize]
    [Route("Setting")]
    public class BasicController : Controller
    {
        private readonly ILogger<BasicController> _logger;
        private readonly ConfigRepository _configRepository;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly string _ViewPath = "~/Views/Setting/Basic.cshtml";

        public BasicController(ILogger<BasicController> logger, ConfigRepository configRepository, UserManager<ApplicationUser> userManager)
        {
            _logger = logger;
            _configRepository = configRepository;
            _userManager = userManager;
        }

        [HttpGet("Basic")]
        public IActionResult Index()
        {
            ViewBag.config = _configRepository.GetAll();

            // 최고 관리자
            ViewBag.Admin = _userManager.GetUsersInRoleAsync("Admin").Result?.ToList();

            return View(_ViewPath);
        }

        [HttpPost("Basic")]
        public IActionResult Save(BasicForm request)
        {
            string message;

            if (!ModelState.IsValid)
            {
                message = "기본 설정 값 저장에 실패";
                _logger.LogWarning(message);
                TempData["ErrorMessages"] = message;
                return View(_ViewPath, request);
            }

            Func.SaveConfig(request, _configRepository.Replace);

            message = "기본 설정 값이 정상적으로 저장되었습니다.";
            _logger.LogInformation(message);
            TempData["SuccessMessage"] = message;
            return RedirectToAction("Index");
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
