using System;
using System.Runtime.InteropServices;
using System.Text;
using PSO2SERVER.Models;
using PSO2SERVER.Protocol.Packets;

namespace PSO2SERVER.Protocol.Handlers
{
    [PacketHandlerAttr(0x23, 0x0B)]
    public class SkitItemAddRequest : PacketHandler
    {
        public struct SkitItemAddRequestPacket
        {
            // Skit name - fixed length of 0x20 bytes (32 bytes).
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
            public byte[] skit_name;

            // Unknown field (u32)
            public uint unk;

            // 初始化字段的构造函数
            public SkitItemAddRequestPacket(string skitName, uint unkValue)
            {
                // Initialize skit_name with a fixed size (32 bytes)
                skit_name = new byte[0x20];

                // Convert the skitName string to ASCII bytes and copy to the skit_name array
                byte[] nameBytes = Encoding.ASCII.GetBytes(skitName);
                Array.Copy(nameBytes, skit_name, Math.Min(nameBytes.Length, 0x20));

                // Set the unk field
                unk = unkValue;
            }

            // Optional: Method to get the skit_name as a string
            public string GetSkitName()
            {
                // Convert the byte array back to a string, stripping off any padding (null characters)
                return Encoding.ASCII.GetString(skit_name).TrimEnd('\0');
            }
        }

        public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size)
        {
            //var info = string.Format("[<--] 接收到的数据 (hex): {0} 字节", data.Length);
            //Logger.WriteHex(info, data);
            // 提取 skit_name 和 unk 字段
            byte[] skitNameBytes = new byte[0x20];
            Array.Copy(data, position, skitNameBytes, 0, 0x20);
            uint unk = BitConverter.ToUInt32(data, (int)(position + 0x20));

            // 创建一个 SkitItemAddRequestPacket 实例
            var packet = new SkitItemAddRequestPacket(Encoding.ASCII.GetString(skitNameBytes).TrimEnd('\0'), unk);

            // 打印处理结果（仅作示例）
            Console.WriteLine("Skit Name: " + packet.GetSkitName());
            Console.WriteLine("Unk Value: " + packet.unk);

            context.SendPacket(new SkitItemAddResponsePacket(packet.GetSkitName(), packet.unk));
        }
    }
}
