public Interfaces.ISocketWrapper Create(Socket socket)
 {
     BufferSize = 8000;
     Socket = new WinSocket(socket);
     Buffer = new byte[BufferSize];
     return this;
 }
 public AuthState(WinSocket socket)
 {
     _socket = socket;
     Alive = true;
 }
        private void ShutDown()
        {
            try
            {
                if (Disconnected)
                    return;
                if (Logger != null)
                {
                    Logger.Close();
                    Logger = null;
                }

                if (this != null && this.Entity != null)
                {
                    if (this.JustCreated)
                        return;
                    if (ServerBase.Kernel.GamePool.ContainsKey(Account.EntityID))
                    {
                        ServerBase.Kernel.GamePool.Remove(Account.EntityID);
                    }
                    if (ServerBase.Kernel.WasInGamePool.ContainsKey(Account.EntityID))
                    {
                        ServerBase.Kernel.WasInGamePool.Remove(Account.EntityID);
                    }
                    //if (ServerBase.Kernel.AwaitingPool.ContainsKey(Account.EntityID))
                    //{
                    //    ServerBase.Kernel.AwaitingPool.Remove(Account.EntityID);
                    //}
                    Time32 now = Time32.Now;
                    RemoveScreenSpawn(this.Entity, false);
                    /* for (byte i = 1; i < 12; i++)
                     {
                         Interfaces.IConquerItem item = this.Equipment.TryGetItem(i);
                         if (item != null && item.ID != 0)
                         {
                             Database.ConquerItemTable.PonerDurabilidad(item);
                         }
                     }*/
                    if (this.Entity.ContainsFlag2(Network.GamePackets.Update.Flags2.CaryingFlag))
                    {

                        Game.Team.RedCapture = false;
                        Game.Team.BlueCapture = false;
                        Game.Team.BlackCapture = false;
                        Game.Team.WhiteCapture = false;
                    }
                    if (this.Entity.ContainsFlag(Update.Flags.Dead))
                    {
                        if (this.Entity.MapID == 1038 && DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                        {
                            if (DateTime.Now.Hour >= 19 && DateTime.Now.Hour < 20 && DateTime.Now.Minute > 29)
                            {
                                this.Entity.Teleport(6001, 31, 74);
                            }
                        }
                    }

                    if (Booth != null)
                    {
                        Booth.Remove();
                    }

                    //Database.SubClassTable.save(this.Entity);
                    //Database.FlowerSystemTable.SaveFlowerTable(this);

                    if (Companion != null)
                    {
                        Map.RemoveEntity(Companion);
                        Data data = new Data(true);
                        data.UID = Companion.UID;
                        data.ID = Data.RemoveEntity;
                        Companion.MonsterInfo.SendScreen(data);
                    }
                    if (QualifierGroup != null)
                        QualifierGroup.End(this);

                    if (ArenaStatistic.Status != Network.GamePackets.ArenaStatistic.NotSignedUp)
                        Game.ConquerStructures.Arena.QualifyEngine.DoQuit(this);

                    Database.FlowerSystemTable.SaveFlowerTable(this);
                    Database.EntityTable.SaveEntity(this);

                    Database.SkillTable.SaveProficiencies(this);
                    Database.SkillTable.SaveSpells(this);

                    Database.ArenaTable.SaveArenaStatistics(this.ArenaStatistic);

                    RemoveScreenSpawn(this.Entity, false);
                    Database.EntityTable.UpdateOnlineStatus(this, false);

                    string name200 = Entity.Name;
                    string name300 = Entity.NewName;
                    if (Entity.NewName != "")
                    {
                        // Console.WriteLine("Change Name In Progress");
                        if (Entity.NewName != "")
                        {
                            PhoenixProject.Database.MySqlCommand cmdupdate = null;
                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("apprentice").Set("MentorName", Entity.NewName).Where("MentorID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("apprentice").Set("ApprenticeName", Entity.NewName).Where("ApprenticeID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("elitepk").Set("Name", Entity.NewName).Where("UID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopArcher", Entity.NewName).Where("TopArcher", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopPirate", Entity.NewName).Where("TopPirate", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopTrojan", Entity.NewName).Where("TopTrojan", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopGuildLeader", Entity.NewName).Where("TopGuildLeader", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopNinja", Entity.NewName).Where("TopNinja", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopMonk", Entity.NewName).Where("TopMonk", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopWarrior", Entity.NewName).Where("TopWarrior", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopSpouse", Entity.NewName).Where("TopSpouse", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopWaterTaoist", Entity.NewName).Where("TopWaterTaoist", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopFireTaoist", Entity.NewName).Where("TopFireTaoist", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("MonthlyPkChampion", Entity.NewName).Where("MonthlyPkChampion", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("WeeklyPkChampion", Entity.NewName).Where("WeeklyPkChampion", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopDeputyLeader", Entity.NewName).Where("TopDeputyLeader", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopDeputyLeader2", Entity.NewName).Where("TopDeputyLeader2", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopDeputyLeader3", Entity.NewName).Where("TopDeputyLeader3", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopDeputyLeader4", Entity.NewName).Where("TopDeputyLeader4", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("flags").Set("TopDeputyLeader5", Entity.NewName).Where("TopDeputyLeader5", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("arena").Set("EntityName", Entity.NewName).Where("EntityID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("claimitems").Set("OwnerName", Entity.NewName).Where("OwnerName", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("claimitems").Set("GainerName", Entity.NewName).Where("GainerName", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("detaineditems").Set("OwnerName", Entity.NewName).Where("OwnerName", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("detaineditems").Set("GainerName", Entity.NewName).Where("GainerName", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("enemy").Set("EnemyName", Entity.NewName).Where("EnemyID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("friends").Set("FriendName", Entity.NewName).Where("FriendID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("guilds").Set("Name", Entity.NewName).Where("Name", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("guilds").Set("LeaderName", Entity.NewName).Where("LeaderName", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("clans").Set("Leader", Entity.NewName).Where("Leader", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("nobility").Set("EntityName", Entity.NewName).Where("EntityUID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("partners").Set("PartnerName", Entity.NewName).Where("PartnerID", Entity.UID).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("entities").Set("Spouse", Entity.NewName).Where("Spouse", Entity.Name).Execute();

                            cmdupdate = new PhoenixProject.Database.MySqlCommand(PhoenixProject.Database.MySqlCommandType.UPDATE);
                            cmdupdate.Update("entities").Set("Name", Entity.NewName).Where("Name", Entity.Name).Execute();

                            if (Game.ConquerStructures.Nobility.Board.ContainsKey(Entity.UID))
                            {
                                Game.ConquerStructures.Nobility.Board[Entity.UID].Name = Entity.NewName;
                            }
                            if (Game.ConquerStructures.Arena.ArenaStatistics.ContainsKey(Entity.UID))
                            {
                                Game.ConquerStructures.Arena.ArenaStatistics[Entity.UID].Name = Entity.NewName;
                            }

                            if (Guild != null)
                            {
                                if (Guild.LeaderName == name200)
                                {
                                    ServerBase.Kernel.Guilds[Guild.ID].LeaderName = Entity.NewName;
                                    ServerBase.Kernel.Guilds[Guild.ID].Members[Entity.UID].Name = Entity.NewName;
                                }
                            }
                            if (Entity.ClanId != 0 && Entity.Myclan != null)
                            {
                                if (Entity.Myclan.ClanLider == name200)
                                {
                                    PhoenixProject.ServerBase.Kernel.ServerClans[Entity.ClanId].ClanLider = Entity.NewName;
                                    PhoenixProject.ServerBase.Kernel.ServerClans[Entity.ClanId].Members[Entity.UID].Name = Entity.NewName;
                                }
                            }
                            //foreach (Client.GameState c in ServerBase.Kernel.GamePool.Values)
                            //{
                            //   if(c.Enemy.ContainsKey(Entity.UID))
                            //    {

                            //        var packet = new KnownPersons(true)
                            //        {
                            //            UID = Entity.UID,
                            //            Type = KnownPersons.RemovePerson,
                            //            Name = name200,
                            //            Online = false
                            //        };
                            //        c.Send(packet);
                            //        c.Enemy[Entity.UID].Name = Entity.NewName;
                            //        packet.Type = KnownPersons.AddEnemy;
                            //        c.Send(packet);
                            //    }
                            //}
                        }
                    }

                    #region Friend/TradePartner/Apprentice
                    Message msg = new Message("Your friend, " + name200 + ", has logged off.", System.Drawing.Color.Red, Message.TopLeft);
                    if (Friends == null)
                        Friends = new SafeDictionary<uint, PhoenixProject.Game.ConquerStructures.Society.Friend>(100);
                    foreach (Game.ConquerStructures.Society.Friend friend in Friends.Values)
                    {
                        if (friend.IsOnline)
                        {
                            var packet = new KnownPersons(true)
                            {
                                UID = Entity.UID,
                                Type = KnownPersons.RemovePerson,
                                Name = name200,
                                Online = false
                            };
                            friend.Client.Send(packet);
                            if (Entity.NewName != "")
                            {
                                if (friend.Client.Friends.ContainsKey(Entity.UID))
                                {
                                    friend.Client.Friends[Entity.UID].Name = Entity.NewName;
                                }
                            }
                            packet.Type = KnownPersons.AddFriend;
                            if (friend != null)
                            {
                                if (friend.Client != null)
                                {
                                    friend.Client.Send(packet);
                                    friend.Client.Send(msg);
                                }
                            }
                        }
                    }
                    Message msg2 = new Message("Your partner, " + name200 + ", has logged off.", System.Drawing.Color.Red, Message.TopLeft);

                    foreach (Game.ConquerStructures.Society.TradePartner partner in Partners.Values)
                    {
                        if (partner.IsOnline)
                        {
                            var packet = new TradePartner(true)
                            {
                                UID = Entity.UID,
                                Type = TradePartner.BreakPartnership,
                                Name = name200,
                                HoursLeft = (int)(new TimeSpan(partner.ProbationStartedOn.AddDays(3).Ticks).TotalHours - new TimeSpan(DateTime.Now.Ticks).TotalHours),
                                Online = false
                            };
                            partner.Client.Send(packet);
                            if (Entity.NewName != "")
                            {
                                if (partner.Client.Partners.ContainsKey(Entity.UID))
                                {
                                    partner.Client.Partners[Entity.UID].Name = Entity.NewName;
                                }
                            }

                            packet.Type = TradePartner.AddPartner;
                            if (partner != null)
                            {
                                if (partner.Client != null)
                                {
                                    partner.Client.Send(packet);
                                    partner.Client.Send(msg2);
                                }
                            }
                        }
                    }
                    MentorInformation Information = new MentorInformation(true);
                    Information.Mentor_Type = 1;
                    Information.Mentor_ID = Entity.UID;
                    Information.Mentor_Level = Entity.Level;
                    Information.Mentor_Class = Entity.Class;
                    Information.Mentor_PkPoints = Entity.PKPoints;
                    Information.Mentor_Mesh = Entity.Mesh;
                    Information.Mentor_Online = false;
                    Information.String_Count = 3;
                    Information.Mentor_Name = name200;
                    Information.Mentor_Spouse_Name = Entity.Spouse;
                    foreach (var appr in Apprentices.Values)
                    {
                        if (appr.IsOnline)
                        {
                            Information.Apprentice_ID = appr.ID;
                            Information.Enrole_Date = appr.EnroleDate;
                            Information.Apprentice_Name = appr.Name;
                            appr.Client.Send(Information);
                            appr.Client.ReviewMentor();
                            if (Entity.NewName != "")
                            {
                                if (appr.Client.Apprentices.ContainsKey(Entity.UID))
                                {
                                    appr.Client.Apprentices[Entity.UID].Name = Entity.NewName;
                                }
                            }
                        }
                    }
                    if (Mentor != null)
                    {
                        if (Mentor.IsOnline)
                        {
                            ApprenticeInformation AppInfo = new ApprenticeInformation();
                            AppInfo.Apprentice_ID = Entity.UID;
                            AppInfo.Apprentice_Level = Entity.Level;
                            AppInfo.Apprentice_Name = name200;
                            AppInfo.Apprentice_Online = false;
                            AppInfo.Apprentice_Spouse_Name = Entity.Spouse;
                            AppInfo.Enrole_date = Mentor.EnroleDate;
                            AppInfo.Mentor_ID = Mentor.Client.Entity.UID;
                            AppInfo.Mentor_Mesh = Mentor.Client.Entity.Mesh;
                            AppInfo.Mentor_Name = Mentor.Client.Entity.Name;
                            AppInfo.Type = 2;
                            Mentor.Client.Send(AppInfo);
                        }
                    }

                    #endregion
                    if (Team != null)
                    {
                        if (Team.TeamLeader)
                        {
                            Network.GamePackets.Team team = new Team();
                            team.UID = Account.EntityID;
                            team.Type = Network.GamePackets.Team.Dismiss;
                            foreach (Client.GameState Teammate in Team.Teammates)
                            {
                                if (Teammate != null)
                                {
                                    if (Teammate.Entity.UID != Account.EntityID)
                                    {
                                        Teammate.Send(team);
                                        Teammate.Team = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            Network.GamePackets.Team team = new Team();
                            team.UID = Account.EntityID;
                            team.Type = Network.GamePackets.Team.ExitTeam;
                            foreach (Client.GameState Teammate in Team.Teammates)
                            {
                                if (Teammate != null)
                                {
                                    if (Teammate.Entity.UID != Account.EntityID)
                                    {
                                        Teammate.Send(team);
                                        Teammate.Team.Remove(Account.EntityID);
                                    }
                                }
                            }
                        }
                    }
                    if (Account.TempID == 400)
                    {
                        Account.EntityID = 0;
                        Account.Save();
                    }
                    if (!Disconnected)
                    {
                        Console.WriteLine(this.Entity.Name + " has logged off! Ip:[" + this.Account.IP + "]");
                        Console.Title = "[" + Database.rates.servername + "]Kimo Proj. Start time: " + Program.StartDate.ToString("dd MM yyyy hh:mm") + ". Players online: " + ServerBase.Kernel.GamePool.Count + "/" + Program.PlayerCap + " Max Online: " + Program.MaxOn + "";
                    }
                    Disconnected = true;
                    try
                    {
                        if (_socket != null)
                        {
                            // Console.WriteLine(" Close1 ");
                            if (_socket.Connected)
                            {
                                // Console.WriteLine(" Close2 ");
                                if (!SocketDisposed)
                                {
                                    //Monitor.Exit(_socket);
                                    // Monitor.Exit(Cryptography);
                                    // Console.WriteLine(" Close3 ");
                                    SocketDisposed = true;
                                    _socket.Disconnect(false);
                                    _socket.Shutdown(SocketShutdown.Both);
                                    _socket.Close();
                                    _socket = null;
                                }
                            }

                        }
                    }
                    catch (Exception e)
                    {
                        Program.SaveException(e);
                        //Disabled = true;
                    }

                }
            }
            catch (Exception e)
            {
                Program.SaveException(e);
                if (ServerBase.Kernel.GamePool.ContainsKey(Account.EntityID))
                {
                    ServerBase.Kernel.GamePool.Remove(Account.EntityID);
                }
                if (ServerBase.Kernel.WasInGamePool.ContainsKey(Account.EntityID))
                {
                    ServerBase.Kernel.WasInGamePool.Remove(Account.EntityID);
                }
                //if (ServerBase.Kernel.AwaitingPool.ContainsKey(Account.EntityID))
                //{
                //    ServerBase.Kernel.AwaitingPool.Remove(Account.EntityID);
                //}
                RemoveScreenSpawn(this.Entity, false);
                Database.EntityTable.UpdateOnlineStatus(this, false);
                if (Account.TempID == 400)
                {
                    Account.EntityID = 0;
                    Account.Save();
                }
                if (!Disconnected)
                {
                    Console.WriteLine(this.Entity.Name + " has logged off! Ip:[" + this.Account.IP + "] Temp");
                    Console.Title = "[" + Database.rates.servername + "]Kimo Proj. Start time: " + Program.StartDate.ToString("dd MM yyyy hh:mm") + ". Players online: " + ServerBase.Kernel.GamePool.Count + "/" + Program.PlayerCap + " Max Online: " + Program.MaxOn + "";
                }
                Disconnected = true;
                try
                {
                    if (_socket != null)
                    {
                        // Console.WriteLine(" Close1 ");
                        if (_socket.Connected)
                        {
                            // Console.WriteLine(" Close2 ");
                            if (!SocketDisposed)
                            {

                                SocketDisposed = true;
                                _socket.Disconnect(false);
                                _socket.Shutdown(SocketShutdown.Both);
                                _socket.Close();
                                _socket = null;
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    Program.SaveException(ex);
                    //Disabled = true;
                }

            }
        }
        public void Disconnect()
        {
            if (Disconnected)
                return;

            try
            {
                if (_socket != null)
                {

                    if (_socket.Connected)
                    {

                        if (!SocketDisposed)
                        {
                            SocketDisposed = true;
                            _socket.Disconnect(false);
                            _socket.Shutdown(SocketShutdown.Both);
                            _socket.Close();
                            _socket = null;
                        }
                    }

                }
                else if (Socket != null)
                {
                    if (Socket.Connected)
                    {

                        if (SocketDisposed)
                        {
                            SocketDisposed = true;
                            Socket.Disconnect(false);
                            Socket.Shutdown(SocketShutdown.Both);
                            Socket.Close();
                        }
                    }

                }
            }
            catch (Exception e)
            {
                Program.SaveException(e);
            }
            if (this.Screen != null)
            {
                if (this.Screen.MyTimer != null)
                {

                    this.Screen.MyTimer.Close();
                    this.Screen.MyTimer.Dispose();
                }
            }
            if (this.Entity != null)
            {
                if (this.Entity.MyTimer != null)
                {
                    this.Entity.MyTimer.Close();
                    this.Entity.MyTimer.Dispose();
                }

            }
            ShutDown();
        }
        public GameState(WinSocket socket)
        {
            Attackable = false;
            Action = 0;
            _socket = socket;

            Cryptography = new GameCryptography(System.Text.ASCIIEncoding.ASCII.GetBytes(ServerBase.Constants.GameCryptographyKey));
            DHKeyExchance = new Network.GamePackets.DHKeyExchange.ServerKeyExchange();
        }