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;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IdentityModel.Tokens.Jwt;
using static backstage.Models.Enums;
using Newtonsoft.Json.Linq;
using System.Text;

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;
        // 在您的類別中注入 IWebHostEnvironment 服務
        private readonly IWebHostEnvironment _webHostEnvironment;
        /// <summary>
        /// 讀取組態用
        /// </summary>

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


        [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(string key_name, string key1, string key2)
        {
            var result = new ResultModel();
            string msg;

			#region name空值檢查
			if (string.IsNullOrEmpty(key_name))
            {
                result.IsSuccess = false;

                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Key name is empty.";
                        break;
                    case "zh":
                        msg = "鑰匙名稱不得為空";
                        break;
                    default:
                        msg = "鑰匙名稱不得為空";
                        break;
                }
                result.Message = msg;
                return result;
            }
            #endregion

            #region name重複檢查
            result = await CheckNameRepeat(key_name);
            if (!result.IsSuccess)
            {
                return result;
			}
            #endregion

            

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

			};

			if (!string.IsNullOrEmpty(key1) && !string.IsNullOrEmpty(key1))
            {
                parameters = new Dictionary<string, string>
                {
                   { "QRData","["+key1+","+key2+"]"}
                };
            }
            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
                    var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if (Response.r == 0)
                    {
                        var keys = Response.QRData;

						#region 回傳兩張qrcode(棄用)
						/*
                        // 取得 wwwroot 資料夾的絕對路徑
                        string wwwrootPath = _webHostEnvironment.WebRootPath;

                        // 確認儲存圖檔的目標資料夾存在，如果不存在則建立它
                        string imagesFolder = Path.Combine(wwwrootPath, "images");
                        Directory.CreateDirectory(imagesFolder);
                        List<string> downloadPaths = new List<string>();
                        for (int i = 0; i < Response.img.Length; i++)
                        {
                            string imageUrl = Response.img[i];
                            string fileName = $"key_part{i + 1}.png";
                            string imagePath = Path.Combine(imagesFolder, fileName);

                            using (HttpClient client = new HttpClient())
                            {
                                // 下載圖檔位元組數據
                                byte[] imageBytes = await client.GetByteArrayAsync(imageUrl);
                                System.IO.File.Delete(imagePath);
                                // 將圖檔寫入目標路徑
                                System.IO.File.WriteAllBytes(imagePath, imageBytes);
                                // 添加下載路徑到集合中
                                if (System.IO.File.Exists(imagePath))
                                {
                                    string downloadPath = Path.Combine("/images", fileName);
                                    downloadPaths.Add(downloadPath);
                                }
                            }
                        }
                        
                        result.Data = downloadPaths;
                        */
						#endregion

						#region step2 combine key
						url = _config["IP"] + "/security/key/combine";

                        parameters = new Dictionary<string, string>
                        {
                             { "name", key_name}
                        };

                        apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                        if (apiResult.IsSuccess)
                        {
                            try
                            {
                                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;
                                    }

                                    /*var ktList = new List<KeyToken>();
									var handler = new JwtSecurityTokenHandler();
									foreach (var key in keys)
                                    {
										byte[] bytes = Convert.FromBase64String(key);
										// 將位元組陣列轉換為原始字串
										string decodedStr = Encoding.UTF8.GetString(bytes);
										var kt = JsonConvert.DeserializeObject<KeyToken>(decodedStr);
                                        kt.Key = key;
										ktList.Add(kt);
									}*/
									result.IsSuccess = true;
                                    result.Message = msg;
                                    //result.Data = ktList;// 回傳兩把key
                                    result.Data = keys;
									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;
                            }

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


                    }
                    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;
                }

            }
            else
            {

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



        }



        /// <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



        }




        /// <summary>
        /// ajax 編輯鑰匙
        /// </summary>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> EditKey(int keyId, string name, int active, int deletable)
        {
            var result = new ResultModel();
            string msg;

			#region name重複檢查
			result = await CheckNameRepeat(name, keyId);
			if (!result.IsSuccess)
			{
				return result;
			}
			#endregion

			#region key/list
			var url = _config["IP"] + "/security/key";
            var httpMethod = HttpMethod.Put;
            var parameters = new Dictionary<string, string>
            {
             { "id", keyId.ToString()},
             { "name", name},
             { "active", active.ToString()},
			 { "del", deletable.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 = "Edit 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>
		/// 檢查name重複
		/// </summary>
		/// <param name="name"></param>
		/// <param name="id">預設值:0，檢查時跳過自己</param>
		/// <returns></returns>
		public async Task<ResultModel> CheckNameRepeat(string name, int id = 0)
        {
            var result = new ResultModel();
            result.IsSuccess = true;
			var msg = "";
			
			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
				{
					var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
					if (response.r == 0)
					{
						var keylist = JsonConvert.DeserializeObject<List<Key>>(response.d.ToString());
						var keyNameRepeat = keylist.Where(x => x.name == name).FirstOrDefault();

						if (keyNameRepeat != null && keyNameRepeat.id != id)
						{
							result.IsSuccess = false;
							switch (_currentLanguage)
							{
								case "en":
									msg = "key name already exists.";
									break;
								case "zh":
									msg = "鑰匙名稱已存在";
									break;
								default:
									msg = "鑰匙名稱已存在";
									break;
							}
							result.Message = msg;
							return result;
						}
					}
					else
					{
						result.IsSuccess = false;
						result.Message = "error.";
						return result;
					}
				}
				catch (Exception e)
				{
					result.IsSuccess = false;
					result.Message = "error.";
					return result;
				}
			}
			else
			{
				result.IsSuccess = false;
				result.Message = "error.";
				return result;
			}

            return result;
		}


		/// <summary>
		/// 啟用KEY ajax
		/// </summary>
		/// <returns></returns>
		[Authorize(Policy = "AdminOnly")]
		[HttpPost]
		public async Task<ResultModel> EnableKey(string keyId)
        {
			var result = new ResultModel();
			string msg;
			var url = _config["IP"] + "/security/key";
			var httpMethod = HttpMethod.Put;
			var parameters = new Dictionary<string, string>
			{
			 { "id", keyId.ToString()},
			 { "active", "1"},
			};

			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 = "Enable 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;
		}
	}
}