using CrazyStudio.Core.Common.AliyunExt.Oss.Tools;
using CrazyStudio.Core.Common.Eitities;
using CrazyStudio.Core.Common.Tools;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Concurrent;
using System.Text.Json;
using System.Threading.Tasks;
using TouchSocket.Core;
using XPrintServer.Api.Dto;
using XPrintServer.Api.Entities.Vol;
using XPrintServer.Api.Tools;

namespace XPrintServer.Api.Controllers.Ai
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SvgController : ControllerBase
    {
        private readonly AliyunInfos _aliyunInfos;
        private readonly OssTool _ossTool;
        private readonly ColorVectorConverter _svgConverter;

        public SvgController(ColorVectorConverter svgConverter, AliyunInfos aliyunInfos, OssTool ossTool)
        {
            _aliyunInfos = aliyunInfos;
            _svgConverter = svgConverter;
            _ossTool = ossTool;
        }




        [HttpPost]
        public async Task<ImageRequestResult?> ConvertToSvg([FromBody] SvgRequestInfo requestInfo)
        {
            string outputSvgPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"SvgTemp/{Guid.NewGuid()}.svg");
            string dict = Path.GetDirectoryName(outputSvgPath)!;
            if (!Directory.Exists(dict))
            {
                Directory.CreateDirectory(dict);
            }

            Enum.TryParse(typeof(DitheringType), requestInfo.Dithering, out var ditheringType);

            float prescale = 1.0f;
            if (requestInfo.IsScaleIn)
            {
                prescale = 2.0f;
            }
            // 转换图像（保留透明度，最多256种颜色）
            await _svgConverter.ConvertToSvg(requestInfo.Url, outputSvgPath, requestInfo.ColorCount, prescale, QuantizationAlgorithm.MedianCut, (DitheringType)ditheringType!, requestInfo.IsStackTracing);

            if (string.IsNullOrWhiteSpace(requestInfo.ObjectName))
            {
                string prefixUrlHttp = $"https://{_aliyunInfos.Oss.Bucket}.{_aliyunInfos.Oss.Region.Replace("-internal", "")}.aliyuncs.com/";
                string prefixUrlHttps = $"https://{_aliyunInfos.Oss.Bucket}.{_aliyunInfos.Oss.Region.Replace("-internal", "")}.aliyuncs.com/";
                string delecteObjectName = requestInfo.Url.Replace(prefixUrlHttps, string.Empty).Replace(prefixUrlHttp, string.Empty);
                _ossTool.DeleteObject(_aliyunInfos.Oss.Bucket, delecteObjectName);
            }
            else
            {
                _ossTool.DeleteObject(_aliyunInfos.Oss.Bucket, requestInfo.ObjectName);
            }
            if (System.IO.File.Exists(outputSvgPath))
            {
                byte[] bytes = System.IO.File.ReadAllBytes(outputSvgPath);
                var objectName = $"cache/svg/{Guid.NewGuid().ToString("N")}.svg";
                using (var mem = new MemoryStream(bytes!))
                {
                    _ossTool.PutObject(_aliyunInfos.Oss.Bucket, objectName, mem, DateTime.UtcNow.AddDays(7));
                }
                System.IO.File.Delete(outputSvgPath);

                string url = $"https://{_aliyunInfos.Oss.Bucket}.{_aliyunInfos.Oss.Region.Replace("-internal", "")}.aliyuncs.com/{objectName}";

                return new ImageRequestResult
                {
                    ImageUrl = url,
                    ObjectName = objectName,
                };
            }
            return null;
        }
    }
}
