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;

namespace backstage.Controllers
{


    [Authorize]
    public class KeyController : Controller
    {

        private readonly IConfiguration _config;
        private readonly ICallApi _callApi;
        /// <summary>
        /// 讀取組態用
        /// </summary>

        public KeyController(IConfiguration config, ICallApi callApi)
        {
            _config = config;
            _callApi = callApi;
        }


        [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



        }






    }
}