using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace XF.Domain.Extensions
{
    public static class StringExtensions
    {
        public static string ToSnakeCase(this string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException(nameof(name));
            var sb = new StringBuilder();
            sb.Append(char.ToLower(name[0]));
            for (int i = 1; i < name.Length; i++)
            {
                if (char.IsUpper(name[i]))
                {
                    sb.Append('_');
                    sb.Append(char.ToLower(name[i]));
                }
                else
                {
                    sb.Append(name[i]);
                }
            }
            return sb.ToString();
        }

        public static string UpperFirstChar(this string str)
        {
            if (string.IsNullOrEmpty(str))
                throw new ArgumentNullException(nameof(str));
            var firstChar = str[0];
            if (char.IsUpper(firstChar))
                return str;
            firstChar = char.ToUpper(firstChar);
            str = str.Remove(0, 1);
            return str.Insert(0, firstChar.ToString());
        }

        public static string ToPascalCase(this string str)
        {
            if (string.IsNullOrEmpty(str))
                throw new ArgumentNullException(nameof(str));
            var array = str.Split('.', StringSplitOptions.TrimEntries);
            var sb = new StringBuilder();
            foreach (var item in array)
            {
                sb.Append(item.UpperFirstChar());
            }
            return sb.ToString();
        }

        public static int GetChineseCharLength(this string str)
        {
            if (string.IsNullOrEmpty(str) || str.Length == 0)
                return 0;
            var ascii = new ASCIIEncoding();
            var tempLen = 0;
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }
            return tempLen;
        }

        public static T? TryDeserialize<T>(this string? str)
        {
            if (string.IsNullOrEmpty(str))
                return default;
            T? rsp = default;
            try
            {
                rsp = System.Text.Json.JsonSerializer.Deserialize<T>(str);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Deserialize 失败，{e}");
            }
            return rsp;
        }
    }
}
