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

namespace bitforum.Controllers.System
{
    [Authorize]
    [Route("System")]
    public class TemplateController : Controller
    {
        private readonly ILogger<TemplateController> _logger;
        private readonly IConfigRepository _configRepository;
        private readonly IFileUploadService _fileUploadService;
        private readonly ISetupService _setupService;

        public TemplateController(ILogger<TemplateController> logger, IConfigRepository configRepository, IFileUploadService fileUploadService, ISetupService setupService)
        {
            _logger = logger;
            _configRepository = configRepository;
            _fileUploadService = fileUploadService;
            _setupService = setupService;
        }

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

        [HttpGet("Template/Email")]
        public IActionResult Index()
        {
            ViewBag.Config = _configRepository.GetAll();

            return View("~/Views/System/Template.cshtml");
        }

        [HttpPost("Template")]
        public IActionResult Save(EmailTemplate request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("알림 양식 설정 값 저장에 실패");
                }

                var config = _configRepository.GetAll();

                request.RegisterEmailFormContent = _fileUploadService.UploadEditorAsync(request.RegisterEmailFormContent, config.GetConfig("register_email_form_content"), UploadFolder.Template).Result;
                request.RegistrationEmailFormContent = _fileUploadService.UploadEditorAsync(request.RegistrationEmailFormContent, config.GetConfig("registration_email_form_content"), UploadFolder.Template).Result;
                request.ResetPasswordEmailFormContent = _fileUploadService.UploadEditorAsync(request.ResetPasswordEmailFormContent, config.GetConfig("reset_password_email_form_content"), UploadFolder.Template).Result;
                request.ChangedPasswordEmailFormContent = _fileUploadService.UploadEditorAsync(request.ChangedPasswordEmailFormContent, config.GetConfig("changed_password_email_form_content"), UploadFolder.Template).Result;
                request.WithdrawEmailFormContent = _fileUploadService.UploadEditorAsync(request.WithdrawEmailFormContent, config.GetConfig("withdraw_email_form_content"), UploadFolder.Template).Result;
                request.EmailVerifyFormContent = _fileUploadService.UploadEditorAsync(request.EmailVerifyFormContent, config.GetConfig("email_verify_form_content"), UploadFolder.Template).Result;
                request.ChangedEmailFormContent = _fileUploadService.UploadEditorAsync(request.ChangedEmailFormContent, config.GetConfig("changed_email_form_content"), UploadFolder.Template).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();
        }
    }
}
