using System.Text;

namespace Zerolauncher.util
{
    class SpaceEncoder
    {
        const int mini_index = 48;
        const int max_index = 70;
        const int sec_index = 60;
        static readonly List<char> map = [
            (char)8192,
            (char)8194,
            (char)8196,
            (char)8197,
            (char)8198,
            (char)8199,
            (char)8200,
            (char)8201,
            (char)8202,
            (char)8239,
            (char)8287,
            (char)32
        ];

        public static string? Encode(string hex)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in hex)
            {
                if (mini_index > c && max_index < c)
                {
                    return null;
                }
                if (c < sec_index)
                {
                    sb.Append(map[c - mini_index]);
                }
                else
                {
                    sb.Append(map[11]);
                    sb.Append(map[c - sec_index]);
                }
            }
            if (sb[1] == 8200)
            {
                StringBuilder sb1 = new StringBuilder();
                sb1.Append((char)8193);
                sb1.Append(sb);
                return sb1.ToString();
            }
            return sb.ToString();
        }

        public static string? Decode(string hex, out int counter)
        {
            StringBuilder sb = new StringBuilder();
            bool double_char = false;
            counter = 0;
            foreach (char c in hex)
            {
                if (sb.Length == 64) break;
                if (counter == 0 && c == 8193) continue;
                counter++;
                if (!map.Contains(c)) return null;
                if (c != map[11])
                {
                    int j = map.FindIndex(item => item.Equals(c));
                    if (double_char)
                    {
                        int k = j + sec_index;
                        if (k > max_index) return null;
                        sb.Append((char)k);
                        double_char = false;
                    }
                    else sb.Append((char)(j + mini_index));
                }
                else
                {
                    if (double_char) return null;
                    double_char = true;
                }
            }
            return sb.ToString();
        }
    }
}
