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

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

        public BasicController(ILogger<BasicController> logger, IConfigRepository configRepository, IFileUploadService fileUploadService, ISetupService setupService, UserManager<ApplicationUser> userManager)
        {
            _logger = logger;
            _configRepository = configRepository;
            _fileUploadService = fileUploadService;
            _setupService = setupService;
            _userManager = userManager;
        }

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

        [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)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("기본 설정 값 저장에 실패");
                }

                var config = _configRepository.GetAll();

                request.BlockAlertContent = _fileUploadService.UploadEditorAsync(request.BlockAlertContent, config.GetConfig("block_alert_content"), UploadFolder.Basic, 1).Result;
                request.MaintenanceContent = _fileUploadService.UploadEditorAsync(request.MaintenanceContent, config.GetConfig("maintenance_content"), UploadFolder.Basic, 2).Result;

                Functions.SaveConfig(request, _configRepository.Replace);
                _setupService.RefreshConfigAsync().Wait();

                string message = "기본 설정 값이 정상적으로 저장되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
            }

            return Index();
        }
    }
}
