using Azure.Cosmos;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.Filter;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using Microsoft.Azure.Cosmos.Table;
using TEAMModelOS.SDK.Models;
using System.Dynamic;
using System.Security.Cryptography;
using Microsoft.Identity.Client;

namespace TEAMModelOS.Controllers.Client
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "HiTeach")]
    [Route("sokrate")]
    [ApiController]
    
    public class SokrateController : ControllerBase
    {
        private readonly AzureStorageFactory _azureStorage;
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        private readonly Option _option;

        public SokrateController(
            AzureStorageFactory azureStorage,
            AzureCosmosFactory azureCosmos,
            DingDing dingDing,
            IOptionsSnapshot<Option> option)
        {
            _azureStorage = azureStorage;
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
        }

        [AllowAnonymous]
        [ProducesDefaultResponseType]
        [HttpPost("get-blob-read")]
        public async Task<IActionResult> GetBlobRead(JsonElement request)
        {
            //Debug
            //string json = System.Text.Json.JsonSerializer.Serialize(id_token);
            try
            {
                string id_token = HttpContext.GetXAuth("IdToken");
                if (string.IsNullOrEmpty(id_token)) return BadRequest();
                var jwt = new JwtSecurityToken(id_token);
                if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
                var id = jwt.Payload.Sub;
                string school_code = (request.TryGetProperty("school_code", out JsonElement schoolCodeJson) && !schoolCodeJson.ValueKind.Equals(JsonValueKind.Null)) ? schoolCodeJson.GetString() : string.Empty;
                string teacher_blob_uri_read = string.Empty;
                string teacher_blob_sas_read = string.Empty;
                string school_blob_uri_read = string.Empty;
                string school_blob_sas_read = string.Empty;

                var client = _azureCosmos.GetCosmosClient();
                //取得老師blob sas
                var responsetea = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(id, new PartitionKey("Base"));
                if (responsetea.Status == 200)
                {
                    (teacher_blob_uri_read, teacher_blob_sas_read) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Read); //讀
                }
                //取得學校blob sas
                if (!String.IsNullOrWhiteSpace(school_code))
                {
                    string school_code_blob = school_code.ToLower();
                    var responsesch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code_blob, new PartitionKey("Base"));
                    if (responsesch.Status == 200)
                    {
                        (school_blob_uri_read, school_blob_sas_read) = _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Read); //讀
                    }
                }

                return Ok(new { teacher_blob_sas_read, school_blob_sas_read });

                //驗證ServiceToken
                //string jsonServiceToken = Encoding.UTF8.GetString(Convert.FromBase64String(service_token));
                //ServiceClientInfo ServiceClientInfo = JsonSerializer.Deserialize<ServiceClientInfo>(jsonServiceToken);
                //AuthenticationResult token = await CoreTokenExtensions.CreateAccessToken(ServiceClientInfo.client_id, ServiceClientInfo.client_secret, location);
                //var jwt = new JwtSecurityToken(token.AccessToken);
                //if (CoreTokenExtensions.ValidateAccessToken(jwt)) {}
            }
            catch (Exception ex)
            {
               // await _dingDing.SendBotMsg($"CoreAPI2，{_option.Location}，hiteach/GetTeacherInfo()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        public class ServiceClientInfo
        {
            public string client_id { get; set; }
            public string client_secret { get; set; }
        }


    }
}
