using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Generic;

using log4net;
using Plus.Database.Interfaces;
using System.Data;


namespace Plus.HabboHotel.Global
{
    public class ServerStatusUpdater : IDisposable
    {
        private static ILog log = LogManager.GetLogger("Plus.Global.ServerUpdater");

        private const int UPDATE_IN_SECS = 30;

        private Timer _timer;
        
        public ServerStatusUpdater()
        {
        }

        public void Init()
        {
            this._timer = new Timer(new TimerCallback(this.OnTick), null, TimeSpan.FromSeconds(UPDATE_IN_SECS), TimeSpan.FromSeconds(UPDATE_IN_SECS));

            Console.Title = "Vanilla - 0 utilisateur(s) - 0 Appart(s) - 0 Jour(s) 0 Heure(s)";

            log.Info("Statut du serveur mise à jours.");
        }

        public void OnTick(object Obj)
        {
            this.UpdateOnlineUsers();
        }

        private void UpdateOnlineUsers()
        {
            TimeSpan Uptime = DateTime.Now - PlusEnvironment.ServerStarted;

            int UsersOnline = Convert.ToInt32(PlusEnvironment.GetGame().GetClientManager().Count);
            int RoomCount = PlusEnvironment.GetGame().GetRoomManager().Count;

            Console.Title = "Vanilla - " + UsersOnline + " utilisateur(s) - " + RoomCount + " Appart(s) - " + Uptime.Days + " Jour(s) " + Uptime.Hours + " Heure(s)";

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("UPDATE `server_status` SET `users_online` = @users, `loaded_rooms` = @loadedRooms WHERE id = 1 LIMIT 1;");
                dbClient.AddParameter("users", UsersOnline);
                dbClient.AddParameter("loadedRooms", RoomCount);
                dbClient.RunQuery();
                DataTable Table = null;
                dbClient.SetQuery("SELECT * FROM server_status WHERE id = '1' LIMIT 1");
                Table = dbClient.getTable();
                foreach (DataRow dRow in Table.Rows)
                {
                    if (Convert.ToInt32(dRow["record_connect"]) < UsersOnline)
                    {
                        dbClient.SetQuery("UPDATE `server_status` SET `record_connect` = @record_connect WHERE id = 1 LIMIT 1;");
                        dbClient.AddParameter("record_connect", UsersOnline);
                        dbClient.RunQuery();
                    }
                }
            }
        }


        public void Dispose()
        {
            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
            }

            this._timer.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
