using System;
using PSO2SERVER.Database;
using System.Data.Entity;
using PSO2SERVER.Models;
using PSO2SERVER.Protocol.Packets;
using static PSO2SERVER.Protocol.Packets.CharacterNewNamePacket;
using System.Linq;

namespace PSO2SERVER.Protocol.Handlers
{
    [PacketHandlerAttr(0x11, 0x9B)]
    public class CharacterNewNameRequest : PacketHandler
    {
        public struct CharacterNewNameRequestPacket
        {
            public uint CharacterID;
            public string Name;
        }

        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);

            if (context._account == null)
                return;

            // 创建一个结构体实例
            var packet = new CharacterNewNameRequestPacket();

            // 读取数据并填充到结构体中
            var reader = new PacketReader(data, position, size);
            packet.CharacterID = reader.ReadUInt32();
            packet.Name = reader.ReadFixedLengthUtf16(16); // 读取16字节长度的名字

            NewNameStatus isdone = NewNameStatus.Failure;

            // 修改数据库字段
            using (var db = new ServerEf())
            {
                // 先检测角色是否存在
                var existingCharacters = db.Characters.Where(c => c.CharacterID == packet.CharacterID && c.AccountID == context._account.AccountId).ToList();
                if (existingCharacters.Count > 0)
                {
                    // 更新角色名字字段
                    var character = existingCharacters.FirstOrDefault();
                    if (character != null)
                    {
                        // 确保名字不为空，并且是16字节长度
                        character.Name = packet.Name.PadRight(16, '\0'); // 确保名字是16字节
                        db.SaveChanges(); // 保存修改
                        isdone = NewNameStatus.Success;
                    }
                }
            }

            context.SendPacket(new CharacterNewNamePacket(isdone, packet.CharacterID, packet.Name));
        }
    }
}
