using System;
using System.Linq;
using PSO2SERVER.Database;
using PSO2SERVER.Models;
using PSO2SERVER.Protocol.Packets;

namespace PSO2SERVER.Protocol.Handlers
{
    [PacketHandlerAttr(0x11, 0xEA)]
    public class NicknameError : PacketHandler
    {
        public struct NicknameErrorPacket
        {
            public uint unk1 {  get; set; }
            public string Nickname {  get; set; }
        }

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

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

            // 读取数据并填充到结构体中
            var reader = new PacketReader(data, position, size);
            packet.unk1 = reader.ReadUInt32();//0x02????
            packet.Nickname = reader.ReadUtf16(0x4544, 0x14); ;

            context._account.Nickname = packet.Nickname;

            // 修改数据库字段
            using (var db = new ServerEf())
            {
                // 先检测角色是否存在
                var existingAccount = db.Accounts.Where(c => c.AccountId == context._account.AccountId).ToList();
                if (existingAccount.Count > 0)
                {
                    // 更新角色名字字段
                    var Account = existingAccount.FirstOrDefault();
                    if (Account != null)
                    {
                        Account.Nickname = packet.Nickname;
                        db.SaveChanges(); // 保存修改
                    }
                }
            }
        }
    }
}
