using Azure.Cosmos;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.Filter;
using TEAMModelOS.SDK.Models.Cosmos;
using HTEXLib.COMM.Helpers;
using TEAMModelOS.SDK.Models.Service;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using TEAMModelOS.SDK;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("tmduser/init")]
    [ApiController]
    public class TmdUserController: ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly AzureStorageFactory _azureStorage;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly IConfiguration _configuration;

        public TmdUserController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration)
        {
            _azureCosmos = azureCosmos;
            _azureStorage = azureStorage;
            _dingDing = dingDing;
            _option = option?.Value;
            _configuration = configuration;
        }
        [ProducesDefaultResponseType]
        [HttpPost("get-school-info")]
        public async Task<IActionResult> GetSchoolInfo(JsonElement request) {

            if (!request.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
            if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
            var jwt = new JwtSecurityToken(id_token.GetString());
            if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
            var id = jwt.Payload.Sub;
            var client = _azureCosmos.GetCosmosClient();
            //權限token
            jwt.Payload.TryGetValue("name", out object name);
            jwt.Payload.TryGetValue("picture", out object picture);
            return Ok();
        }

        [ProducesDefaultResponseType]
        [HttpPost("get-tmduser-info")]
        public async Task<IActionResult> GetTmdUserInfo(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
                var jwt = new JwtSecurityToken(id_token.GetString());
                if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
                var id = jwt.Payload.Sub;
                jwt.Payload.TryGetValue("name", out object name);
                jwt.Payload.TryGetValue("picture", out object picture);
                List<object> schools = new List<object>();
                string defaultschool = null;
                var client = _azureCosmos.GetCosmosClient();
                try
                {
                    TmdUser tmdUser = await client.GetContainer("TEAMModelOS", "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
                    tmdUser.name = $"{name}";
                    tmdUser.picture = $"{picture}";
                    if (tmdUser.schools.IsNotEmpty())
                    {
                        foreach (var sc in tmdUser.schools)
                        {
                             
                            dynamic schoolExtobj = new ExpandoObject();
                            var schoolJson = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{sc.schoolId}", new PartitionKey("Base"));
                            var school = await JsonDocument.ParseAsync(schoolJson.ContentStream);
                            schoolExtobj.schoolId = sc.schoolId;
                            schoolExtobj.name = school.RootElement.GetProperty("name");
                            schoolExtobj.status = sc.status;
                            schoolExtobj.time = sc.time;
                            schoolExtobj.picture = school.RootElement.GetProperty("picture");
                            sc.name= $"{school.RootElement.GetProperty("name")}";
                        }
                        tmdUser.defaultSchool = string.IsNullOrEmpty(tmdUser.defaultSchool) ? tmdUser.schools[0].schoolId : tmdUser.defaultSchool;
                    }
                    await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync<TmdUser>(tmdUser, id, new PartitionKey("Base"));
                    //預設學校ID
                    defaultschool = tmdUser.defaultSchool;
                }
                catch (CosmosException ex)
                {
                    if (ex.Status == 404)
                    {
                        //如果沒有，則初始化Teacher基本資料到Cosmos
                        TmdUser teacher = new TmdUser
                        {
                            id = id,
                            pk = "Base",
                            code = "Base",
                            name = name?.ToString(),
                            picture = picture?.ToString(),
                            defaultSchool = null,
                            schools = new List<TmdUser.School>(),
                        };
                        var container = _azureStorage.GetBlobContainerClient(id);
                        await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器，如存在則不做任何事，保障容器一定存在
                        teacher = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").CreateItemAsync<TmdUser>(teacher, new PartitionKey("Base"));
                    }
                }
                //換取AuthToken，提供給前端
                var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "student" });
                if (!string.IsNullOrEmpty(defaultschool)) { 

                }
                return Ok(new { location=_option.Location ,auth_token,  schools, defaultschool });

            }
            catch (CosmosException ex)
            {
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，Teacher/GetTeacherInfo()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，Teacher/GetTeacherInfo()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
    
        private  async Task<(string uri,string  sas)> GetSchoolData(string shool) {

            // BLOB(學校，唯讀)
            var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(shool, BlobContainerSasPermissions.Read);

            return (blob_uri, blob_sas);
        }
    }
}
