using System.IO;
using System.Data.Entity;
using PSO2SERVER.Models;
using PSO2SERVER.Protocol.Packets;
using PSO2SERVER.Database;
using System.Linq;
using static PSO2SERVER.Models.CharacterStruct;
using System.Security.Cryptography.Pkcs;
using System.Runtime.InteropServices;

namespace PSO2SERVER.Protocol.Handlers
{
    [PacketHandlerAttr(0x11, 0x05)]
    public class CharacterCreate : PacketHandler
    {
        #region implemented abstract members of PacketHandler

        public struct CharacterCreatePacket
        {
            public int CharacterID;
            public int AccountID;
            public int Unk1;
            public int VoiceType;
            public short Unk2;
            public short VoicePitch;
            public string Name;
            public int Unk3;
            public LooksParam Looks;
            public JobParam Jobs;
            public string unk4;  // 148 字节的字节数组
        }
        
        private CharacterCreatePacket packet = new CharacterCreatePacket();

        public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size)
        {
            if (context._account == null)
                return;

            var reader = new PacketReader(data, position, size);
            var info = string.Format("[<--] 接收到的数据 (hex): {0} 字节", data.Length);
            Logger.WriteHex(info, data);

            packet.CharacterID = reader.ReadInt32();
            packet.AccountID = reader.ReadInt32();
            packet.Unk1 = reader.ReadInt32();//Unk1
            packet.VoiceType = reader.ReadInt32(); // VoiceType
            packet.Unk2 = reader.ReadInt16(); // 5 unknown bytes
            packet.VoicePitch = reader.ReadInt16(); // VoiceData
            packet.Name = reader.ReadFixedLengthUtf16(16);
            packet.Unk3 = reader.ReadInt32();
            packet.Looks = reader.ReadStruct<LooksParam>();
            packet.Jobs = reader.ReadStruct<JobParam>();
            packet.unk4 = reader.ReadFixedLengthUtf16(76);

            var newCharacter = new Character
            {
                CharacterID = 0,
                AccountID = context._account.AccountId,
                Unk1 = packet.Unk1,
                VoiceType = packet.VoiceType,
                Unk2 = packet.Unk2,
                VoicePitch = packet.VoicePitch,
                Name = packet.Name,
                Unk3 = packet.Unk3,
                Jobs = packet.Jobs,
                Looks = packet.Looks,
                Account = context._account,
                fulldata = data
            };

            // Add to database
            using (var db = new ServerEf())
            {
                // Check if any characters exist for this player
                var existingCharacters = db.Characters.Where(c => c.Account.AccountId == context._account.AccountId).ToList();
                if (existingCharacters.Count > 0)
                {
                    // Increment ID if characters already exist
                    newCharacter.CharacterID = existingCharacters.Max(c => c.CharacterID) + 1;
                }
                else
                {
                    // Start with ID 1 if no characters exist
                    newCharacter.CharacterID = 1;
                }

                Logger.Write("New character data: {0}, {1}, {2}, {3}, {4}", newCharacter.CharacterID, newCharacter.Name, newCharacter.VoiceType, newCharacter.VoicePitch, newCharacter.AccountID);

                db.Characters.Add(newCharacter);
                db.Entry(newCharacter.Account).State = EntityState.Modified;
                db.SaveChanges();
            }

            // Assign character to player
            context.Character = newCharacter;

            // Set Accounts ID
            context.SendPacket(new CharacterCreateResponsePacket(CharacterCreateResponsePacket.CharacterCreationStatus.Success, (uint)context._account.AccountId));
        }

        #endregion
    }
}