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

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

        public CompanyController(ILogger<CompanyController> logger, ConfigRepository configRepository)
        {
            _logger = logger;
            _configRepository = configRepository;
        }

        [HttpGet("Company")]
        public IActionResult Index()
        {
            var config = _configRepository.GetAll();
            ViewBag.config = config;
            ViewBag.bankCodes = BankCodeData.List.Select(item => new SelectListItem
                {
                    Value = item.Value,
                    Text = item.Text,
                    Selected = item.Value == config.GetConfig("company_bank_code")
            }).ToList();

            return View(_ViewPath);
        }

        [HttpPost("Company")]
        public IActionResult Save(CompanyForm 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 });
        }
    }
}
