using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Xml.Linq;
using System.IO;
using PSO2SERVER.Protocol;

namespace PSO2SERVER.Models
{
    public class FixedList<T> : IEnumerable<T>
    {
        private List<T> _data;
        private int _capacity;

        public FixedList(int size)
        {
            if (size <= 0)
                throw new ArgumentException("Size must be greater than zero.", nameof(size));

            _data = new List<T>(size);
            _capacity = size;
        }
        public FixedList(int size, T defaultValue)
        {
            if (size <= 0)
                throw new ArgumentException("Size must be greater than zero.", nameof(size));

            _data = new List<T>(size);
            _capacity = size;
            for (int i = 0; i < size; i++)
            {
                _data.Add(defaultValue);
            }
        }

        public int Capacity => _capacity;

        public int Length => _data.Count;

        public void Add(T item)
        {
            if (_data.Count >= _capacity)
                throw new InvalidOperationException("FixedList is full.");

            _data.Add(item);
        }

        public void Insert(int index, T item)
        {
            if (index < 0 || index > _data.Count)
                throw new ArgumentOutOfRangeException(nameof(index));

            if (_data.Count >= _capacity)
                throw new InvalidOperationException("FixedList is full.");

            _data.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            if (index < 0 || index >= _data.Count)
                throw new ArgumentOutOfRangeException(nameof(index));

            _data.RemoveAt(index);
        }

        public void RemoveLast()
        {
            if (_data.Count == 0)
                throw new InvalidOperationException("FixedList is empty.");

            _data.RemoveAt(_data.Count - 1);
        }

        public void SetItem(int index, T value)
        {
            // 如果 index 超出当前长度，但没有超出最大容量，进行扩展
            if (index >= _data.Count)
            {
                // 如果 index 没有超过最大容量
                if (index < _capacity)
                {
                    // 扩展 _data 列表，填充默认值
                    while (_data.Count <= index && _data.Count < _capacity)
                    {
                        _data.Add(default(T));
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException(nameof(index), "索引超出最大容量.");
                }
            }

            // 赋值
            _data[index] = value;
        }

        public void SetListItem(List<T> value)
        {
            // 截取最大容量的值，如果传入的值超过了 _capacity
            if (value.Count > _capacity)
            {
                value = value.Take(_capacity).ToList();
            }

            // 更新已有的元素
            for (var i = 0; i < _data.Count && i < value.Count; i++)
            {
                _data[i] = value[i];
            }

            // 如果 value 的长度超过当前 _data 长度并且未超过最大容量，则扩展 _data 长度
            if (value.Count > _data.Count)
            {
                // 计算要增加的元素数量
                int elementsToAdd = value.Count - _data.Count;

                // 添加元素，确保不超过最大容量
                for (var i = 0; i < elementsToAdd && _data.Count < _capacity; i++)
                {
                    _data.Add(default(T)); // 填充默认值
                }

                // 将传入的 value 中剩余的元素（超出 _data 长度部分）复制到 _data
                for (var i = _data.Count; i < value.Count; i++)
                {
                    _data[i] = value[i];
                }
            }
        }

        public void SetAll(T newValue)
        {
            for (int i = 0; i < _data.Count; i++)
            {
                _data[i] = newValue;
            }
        }

        public void Clear()
        {
            _data.Clear();
        }

        public T this[int index]
        {
            get
            {
                if (index < 0 || index >= _data.Count)
                    throw new IndexOutOfRangeException();
                return _data[index];
            }
            set
            {
                if (index < 0 || index >= _data.Count)
                    throw new IndexOutOfRangeException();
                _data[index] = value;
            }
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _data)}]";
        }

        // 实现 IEnumerable<T> 接口
        public IEnumerator<T> GetEnumerator()
        {
            return _data.GetEnumerator();
        }

        // 非泛型版本的 GetEnumerator
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class FixedSortedList<T> : IEnumerable<T> where T : IComparable<T>
    {
        private List<T> _list;
        private int _capacity;

        public FixedSortedList(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _list = new List<T>();
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count => _list.Count;

        // 添加元素
        public void Add(T item)
        {
            if (_list.Count >= _capacity)
                throw new InvalidOperationException("List is full.");

            _list.Add(item);
            _list.Sort();  // 自动排序
        }

        // 获取元素
        public T Get(int index)
        {
            if (index < 0 || index >= _list.Count)
                throw new ArgumentOutOfRangeException(nameof(index));

            return _list[index];
        }

        // 清空列表
        public void Clear()
        {
            _list.Clear();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _list)}]";
        }

        // 实现 IEnumerable<T> 接口
        public IEnumerator<T> GetEnumerator()
        {
            return _list.GetEnumerator();
        }

        // 非泛型版本的 GetEnumerator
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

    }

    public class FixedHashSet<T> : IEnumerable<T>
    {
        private HashSet<T> _set;
        private int _capacity;

        public FixedHashSet(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _set = new HashSet<T>();
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count => _set.Count;

        // 添加元素
        public bool Add(T item)
        {
            if (_set.Count >= _capacity)
                throw new InvalidOperationException("HashSet is full.");

            return _set.Add(item);
        }

        // 判断元素是否存在
        public bool Contains(T item)
        {
            return _set.Contains(item);
        }

        // 清空集合
        public void Clear()
        {
            _set.Clear();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _set)}]";
        }
        // 实现 IEnumerable<T> 接口
        public IEnumerator<T> GetEnumerator()
        {
            return _set.GetEnumerator();
        }

        // 非泛型版本的 GetEnumerator
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

    }

    public class FixedString
    {
        private string[] _array;
        private int _capacity;

        public FixedString(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new string[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的字符串
        public string this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加字符串
        public void Add(string item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var str in _array.Take(Count))
            {
                byte[] stringBytes = System.Text.Encoding.UTF8.GetBytes(str);
                byteList.AddRange(stringBytes);
            }
            return byteList.ToArray();
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }

    public class FixedInt
    {
        private int[] _array;
        private int _capacity;

        public FixedInt(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new int[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的整数
        public int this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加整数
        public void Add(int item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] intBytes = BitConverter.GetBytes(num);
                byteList.AddRange(intBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }

    public class FixedUlong
    {
        private ulong[] _array;
        private int _capacity;

        public FixedUlong(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new ulong[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的 ulong 数值
        public ulong this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加 ulong 数值
        public void Add(ulong item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] ulongBytes = BitConverter.GetBytes(num);
                byteList.AddRange(ulongBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }
    //public class FixedByte
    //{
    //    private byte[] _array;
    //    private int _capacity;

    //    public FixedByte(int capacity)
    //    {
    //        if (capacity <= 0)
    //            throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

    //        _array = new byte[capacity];
    //        _capacity = capacity;
    //        Count = 0; // 初始化 Count 为 0
    //    }

    //    public int Capacity => _capacity;

    //    // Count 现在是只读属性
    //    public int Count { get; private set; }

    //    // 获取或设置指定索引的字节
    //    public byte this[int index]
    //    {
    //        get
    //        {
    //            if (index < 0 || index >= Count)
    //                throw new ArgumentOutOfRangeException(nameof(index));

    //            return _array[index];
    //        }
    //        set
    //        {
    //            if (index < 0 || index >= Count)
    //                throw new ArgumentOutOfRangeException(nameof(index));

    //            _array[index] = value;
    //        }
    //    }

    //    // 添加字节
    //    public void Add(byte item)
    //    {
    //        if (Count >= _capacity)
    //            throw new InvalidOperationException("Array is full.");

    //        _array[Count++] = item;
    //    }

    //    // 清空数组
    //    public void Clear()
    //    {
    //        Array.Clear(_array, 0, _capacity);
    //        Count = 0;
    //    }

    //    // 将字节数组转换为字节数组（仅返回已使用的部分）
    //    public byte[] ToBytes()
    //    {
    //        return _array.Take(Count).ToArray();
    //    }

    //    public override string ToString()
    //    {
    //        return $"[{string.Join(", ", _array.Take(Count))}]";
    //    }

    //    // JSON 序列化和反序列化的自定义处理
    //    public class FixedByteConverter : JsonConverter<FixedByte>
    //    {
    //        public override FixedByte ReadJson(JsonReader reader, Type objectType, FixedByte existingValue, bool hasExistingValue, JsonSerializer serializer)
    //        {
    //            // 确保是 JSON 数组格式
    //            if (reader.TokenType == JsonToken.StartArray)
    //            {
    //                // 反序列化为字节数组
    //                var byteArray = serializer.Deserialize<byte[]>(reader);
    //                var fixedByte = new FixedByte(byteArray.Length);

    //                // 使用 Add 方法填充字节
    //                foreach (var byteValue in byteArray)
    //                {
    //                    fixedByte.Add(byteValue);
    //                }

    //                return fixedByte;
    //            }
    //            else
    //            {
    //                throw new JsonSerializationException("Expected a JSON array.");
    //            }
    //        }

    //        public override void WriteJson(JsonWriter writer, FixedByte value, JsonSerializer serializer)
    //        {
    //            // 序列化时直接写入字节数组
    //            serializer.Serialize(writer, value.ToBytes());
    //        }
    //    }
    //}

    public class FixedDouble
    {
        private double[] _array;
        private int _capacity;

        public FixedDouble(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new double[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的 double 类型数值
        public double this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加 double 类型数值
        public void Add(double item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] doubleBytes = BitConverter.GetBytes(num);
                byteList.AddRange(doubleBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }
    public class FixedFloat
    {
        private float[] _array;
        private int _capacity;

        public FixedFloat(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new float[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的 float 类型数值
        public float this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加 float 类型数值
        public void Add(float item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] floatBytes = BitConverter.GetBytes(num);
                byteList.AddRange(floatBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }
    public class FixedLong
    {
        private long[] _array;
        private int _capacity;

        public FixedLong(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new long[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的 long 类型数值
        public long this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加 long 类型数值
        public void Add(long item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] longBytes = BitConverter.GetBytes(num);
                byteList.AddRange(longBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }
    public class FixedUShort
    {
        private ushort[] _array;
        private int _capacity;

        public FixedUShort(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new ushort[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的 ushort 类型数值
        public ushort this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加 ushort 类型数值
        public void Add(ushort item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] ushortBytes = BitConverter.GetBytes(num);
                byteList.AddRange(ushortBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }

        public class FixedUShortConverter : JsonConverter<FixedUShort>
        {
            public override FixedUShort ReadJson(JsonReader reader, Type objectType, FixedUShort existingValue, bool hasExistingValue, JsonSerializer serializer)
            {
                // 确保我们读取的是一个 JSON 数组
                if (reader.TokenType != JsonToken.StartArray)
                    throw new JsonSerializationException("Expected StartArray token.");

                JArray array = JArray.Load(reader);
                var fixedUShort = new FixedUShort(array.Count);  // 创建一个合适容量的 FixedUShort 对象

                foreach (var item in array)
                {
                    // 将每个元素添加到 FixedUShort 对象中
                    if (item.Type == JTokenType.Integer)
                    {
                        fixedUShort.Add((ushort)item);
                    }
                    else
                    {
                        throw new JsonSerializationException("Expected ushort values in the array.");
                    }
                }

                return fixedUShort;
            }

            public override void WriteJson(JsonWriter writer, FixedUShort value, JsonSerializer serializer)
            {
                writer.WriteStartArray();
                for (int i = 0; i < value.Count; i++)
                {
                    writer.WriteValue(value[i]);
                }
                writer.WriteEndArray();
            }
        }

    }

    public class FixedShort
    {
        private short[] _array;
        private int _capacity;

        public FixedShort(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentException("Capacity must be greater than zero.", nameof(capacity));

            _array = new short[capacity];
            _capacity = capacity;
        }

        public int Capacity => _capacity;
        public int Count { get; private set; } = 0;

        // 获取或设置指定索引的 ushort 类型数值
        public short this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                return _array[index];
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(nameof(index));

                _array[index] = value;
            }
        }

        // 添加 ushort 类型数值
        public void Add(short item)
        {
            if (Count >= _capacity)
                throw new InvalidOperationException("Array is full.");

            _array[Count++] = item;
        }

        // 清空数组
        public void Clear()
        {
            Array.Clear(_array, 0, _capacity);
            Count = 0;
        }

        // 将数组转换为字节数组
        public byte[] ToBytes()
        {
            List<byte> byteList = new List<byte>();
            foreach (var num in _array.Take(Count))
            {
                byte[] ushortBytes = BitConverter.GetBytes(num);
                byteList.AddRange(ushortBytes);
            }
            return byteList.ToArray();
        }

        public override string ToString()
        {
            return $"[{string.Join(", ", _array.Take(Count))}]";
        }
    }

}
