using CrazyStudio.Core.Common;
using CrazyStudio.Core.Common.Eitities;
using CrazyStudio.Core.Common.Tools;
using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using System.Threading.Tasks;
using XPrintServer.Api.Dto;
using XPrintServer.Api.Entities;
using XPrintServer.Api.Tools;

namespace XPrintServer.Api.Controllers.Aliyun
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AliyunController : ControllerBase
    {
        private static DateTime tokenTime = DateTime.MinValue;
        private static AliyunTokenResult? tokenResult = null;

        private readonly AliyunInfos? _aliyunInfos = null;
        public AliyunController(AliyunInfos aliyunInfos)
        {
            _aliyunInfos = aliyunInfos;
        }

        [HttpPost]
        public async Task<AliyunTokenResultDTO?> GetSoundToken()
        {
            string tokenJson = await AliyunTokenTool.GetAccessTokenAsync(_aliyunInfos!.AccessKeyId, _aliyunInfos!.AccessKeySecret);
            try
            {
                if (tokenResult != null)
                {
                    if (DateTime.UtcNow < tokenTime.AddMinutes(-1))
                    {
                        return new AliyunTokenResultDTO
                        {
                            Token = tokenResult!.Token.Id,
                            SoundAppId = _aliyunInfos.SoundAppId
                        };
                    }
                }
                tokenResult = JsonSerializer.Deserialize<AliyunTokenResult?>(tokenJson);
                if (tokenResult == null)
                {
                    return null;
                }
                tokenTime = DateTimeOffset.FromUnixTimeSeconds(tokenResult.Token.ExpireTime).UtcDateTime;
                return new AliyunTokenResultDTO
                {
                    Token = tokenResult!.Token.Id,
                    SoundAppId = _aliyunInfos.SoundAppId
                };
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
