using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using backstage.Helpers;
using backstage.Models.Keys;

using System.Net.Http;
using System.Security.Claims;
using TokenVault_management.Models;
using backstage.Models;
using Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Http;

namespace backstage.Controllers
{


    [Authorize]
    public class KeyController : Controller
    {

        private readonly IConfiguration _config;
        private readonly ICallApi _callApi;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IStringLocalizer<UserController> _localizer;
        private readonly string _currentLanguage;
        /// <summary>
        /// 讀取組態用
        /// </summary>

        public KeyController(IConfiguration config, ICallApi callApi, IHttpContextAccessor httpContextAccessor, IStringLocalizer<UserController> localizer)
        {
            _config = config;
            _callApi = callApi;
            _httpContextAccessor = httpContextAccessor;
            _localizer = localizer;
            var requestCultureFeature = _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>();
            var currentCulture = requestCultureFeature.RequestCulture.Culture;
            _currentLanguage = currentCulture.TwoLetterISOLanguageName;
        }


        [Authorize(Policy = "AdminOnly")]
        public async Task<IActionResult> ListKeys()
        {
            var ListKeysResponse = new ListKeysResponse();


            #region key/list
            var url = _config["IP"] + "/security/key/list";
            var httpMethod = HttpMethod.Post;
            var parameters = new Dictionary<string, string>
            {

            };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
                    ListKeysResponse = JsonConvert.DeserializeObject<ListKeysResponse>(apiResult.Data.ToString());
                    if (ListKeysResponse.r == 0)
                    {
                        return View(ListKeysResponse.d);
                    }
                    else
                    {
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = ListKeysResponse.m;
                        return View();
                    }
                }
                catch (Exception e)
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = e.Message + e.InnerException?.Message;
                    return View();
                }

            }
            TempData["IsSuccess"] = false;
            TempData["msg"] = apiResult.Message;
            return View();
            #endregion



        }


        /// <summary>
        /// ajax
        /// </summary>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> CreateKey(int keyId)
        {
            var result = new ResultModel();
            string msg;
            #region key/list
            var url = _config["IP"] + "/security/key/generate";
            var httpMethod = HttpMethod.Post;
            var parameters = new Dictionary<string, string>
            {
             
            };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
                    var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if (Response.r == 0)
                    {

                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Create key success.";
                                break;
                            case "zh":
                                msg = "新增鑰匙成功";
                                break;
                            default:
                                msg = "新增鑰匙成功";
                                break;

                        }
                        result.IsSuccess = true;
                        result.Message = msg;
                        return result;
                    }
                    else
                    {

                        result.IsSuccess = false;
                        result.Message = Response.m.ToString();
                        return result;
                    }
                }
                catch (Exception e)
                {
                    result.IsSuccess = false;
                    result.Message = e.Message + e.InnerException?.Message;
                    return result;
                }

            }
            result.IsSuccess = false;
            result.Message = apiResult.Message;
            return result;
            #endregion



        }



        /// <summary>
        /// ajax
        /// </summary>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> DeleteKey(int keyId)
        {
            var result = new ResultModel();
            string msg;
            #region key/list
            var url = _config["IP"] + "/security/key";
            var httpMethod = HttpMethod.Delete;
            var parameters = new Dictionary<string, string>
            {
             { "id",keyId.ToString()},
            };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
                    var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if (Response.r == 0)
                    {

                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Delete key success.";
                                break;
                            case "zh":
                                msg = "鑰匙刪除成功";
                                break;
                            default:
                                msg = "鑰匙刪除成功";
                                break;

                        }
                        result.IsSuccess = true;
                        result.Message = msg;
                        return result;
                    }
                    else
                    {

                        result.IsSuccess = false;
                        result.Message = Response.m.ToString();
                        return result;
                    }
                }
                catch (Exception e)
                {
                    result.IsSuccess = false;
                    result.Message = e.Message + e.InnerException?.Message;
                    return result;
                }

            }
            result.IsSuccess = false;
            result.Message = apiResult.Message;
            return result;
            #endregion



        }


    }
}