using IRaCIS.Core.Application.Helper;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson
{
    public class ObjectStorePathConvert : JsonConverter<string>
    {
        private readonly IOSSService _oSSService;

        // 构造函数
        public ObjectStorePathConvert(IOSSService oSSService)
        {
            _oSSService = oSSService;
        }

        public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return (string)reader.Value;
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
        {
            if (value != null)
            {
                // 在这里对字符串进行处理，例如转换大小写、去除空格等
                // 这里只是一个示例，您可以根据实际需求进行更改

                // 获取当前正在序列化的属性名
                string propertyName = writer.Path.Split('.').Last();

                Regex guidRegex = new Regex(@"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}");

                if (propertyName.IndexOf("Path") > -1 && value.IndexOf('.') > -1 && guidRegex.IsMatch(value))
                {
                    var tt = _oSSService.GetSignedUrl(value);
                    writer.WriteValue(tt);
                }
                else
                {
                    // 将处理后的字符串写入到 JsonWriter 中
                    writer.WriteValue(value);
                }

            }
            else
            {
                writer.WriteNull();
            }
        }

    }
}
