using HiTeachCC.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using TEAMModelOS.SDK.Context.Configuration;
using TEAMModelOS.SDK.Context.Constant.Common;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Module.AzureBlob.Configuration;

namespace HiTeachCC.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [Route("common/login")]
    [ApiController]
    public class LoginController:ControllerBase
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly AzureStorageFactory _azureStorageFactory;
        public LoginController(IHttpClientFactory httpClientFactory, AzureStorageFactory azureStorage) {
            _clientFactory = httpClientFactory;
            _azureStorageFactory = azureStorage;
        }
        /// <summary>
        /// Ticket 
        /// Token  
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("blob-auth")]
        [AllowAnonymous]
        public IActionResult BlobAuth()
        {
            BlobAuth blobAuth = _azureStorageFactory.GetContainerSasUri(new BlobSas { name = "hiteachcc", role = "teacher" }, false);
            return  Ok(blobAuth);
        }  
        
        /// <summary>
        /// Ticket 
        /// Token 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[HttpPost("tmd-login")]
        //[AllowAnonymous]
        //public async Task<IActionResult> TeamModelLogin(TicketInfo ticketInfo)
        //{
        //    if (ticketInfo != null && (string.IsNullOrEmpty(ticketInfo.ticket) || string.IsNullOrEmpty(ticketInfo.token)))
        //    {
        //        return null;
        //    }
        //    string jwttoken = ticketInfo.token.Replace("Bearer ", "");
        //    var request = new
        //    {
        //        method = "UserInfoManage",
        //        jsonrpc = "2.0",
        //        id = 1,
        //        @params = new Dictionary<string, object>
        //        {
        //            { "idToken",ticketInfo.ticket },
        //            { "method", "get" },
        //            { "option", "userInfo"},
        //            { "extraInfo",  new object() }
        //        }
        //    };
        //    string data = request.ToJsonString();
        //    var HttpRequestMessage = new HttpRequestMessage();
        //    HttpRequestMessage.Method = new HttpMethod("POST");
        //    HttpRequestMessage.RequestUri = new Uri(BaseConfigModel.Configuration["HaBookAuth:AccountUrl"]);// new Uri("https://account.teammodel.cn/account");// 
        //    HttpRequestMessage.Content = new StringContent(data);
        //    HttpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        //    HttpRequestMessage.Headers.Add("Authorization", "Bearer " + jwttoken);
        //    var client = _clientFactory.CreateClient();
        //    var response = await client.SendAsync(HttpRequestMessage);
        //    if (response.IsSuccessStatusCode)
        //    {
        //        var RPCResponse = await response.Content.ReadAsAsync<RPCResponse>();
        //        if (RPCResponse != null && RPCResponse.result != null)
        //        {
        //            string blob = RPCResponse.result.id.Replace("#", "").ToLower();
        //            BlobAuth blobAuth = _azureStorageFactory.GetContainerSasUri(new BlobSas { name = "hiteachcc", role = "teacher" }, false);
        //            string idToken = CreateAuthToken("account.teammodel", RPCResponse.result.id, RPCResponse.result.name, RPCResponse.result.profilePictureUrl,
        //                RPCResponse.result.email, blob, blobAuth.name, blobAuth.url, blobAuth.sas, RPCResponse.result.idToken, 24);

        //            return Ok(new { idToken });
        //        }
        //    }

        //    return BadRequest();
        //}

        public static string CreateAuthToken(string issuer, string id, string name, string picture,string email,string folder,string  blob ,string url,string sas, string salt,int expire = 1)
        {
            // 設定要加入到 JWT Token 中的聲明資訊(Claims)  
            var payload = new JwtPayload {
                { JwtRegisteredClaimNames.Iss, issuer }, //發行者
                { JwtRegisteredClaimNames.Sub, id }, // 用戶ID                  
                { JwtRegisteredClaimNames.Exp,DateTimeOffset.UtcNow.AddHours(expire).ToUnixTimeSeconds()},  // 到期的時間，必須為數字
                { "email", email }, // 用戶ID      
                { "name",name}, // 用戶的顯示名稱
                { "picture",picture}, // 用戶頭像
                { "temp",folder+"/temp"},
                { "res",folder+"/res"},
                { "blob",blob},
                { "url",url},
                { "sas",sas},
            };
            // 建立一組對稱式加密的金鑰，主要用於 JWT 簽章之用
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salt));
            // HmacSha256 有要求必須要大於 128 bits，所以 salt 不能太短，至少要 16 字元以上
            // https://stackoverflow.com/questions/47279947/idx10603-the-algorithm-hs256-requires-the-securitykey-keysize-to-be-greater
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var header = new JwtHeader(signingCredentials);
            var secToken = new JwtSecurityToken(header, payload);
            // 產出所需要的 JWT securityToken 物件，並取得序列化後的 Token 結果(字串格式)
            var tokenHandler = new JwtSecurityTokenHandler();
            //var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            var serializeToken = tokenHandler.WriteToken(secToken);
            return serializeToken;
        }
    }

    public class RPCResponse {
        public TeamModelUser result { get; set; }
        public double id { get; set; }
        public string jsonrpc { get; set; }
    }
}
