 using System;
using System.Data;
using System.Threading;
using System.Data.SqlClient;
using System.Collections.Generic;

using FilterAPI.Networking;

namespace FilterTimers.Timers
{
    internal class MoneyTimer
    {
        #region Timer Variables

        private Int32 Interval;
        private Int64 MoneyToGive;
        private String Message;

        #endregion

        private Boolean IsDone = true;

        public MoneyTimer(Int32 I, Int64 MTG, String M)
        {
            Interval = I;
            MoneyToGive = MTG;
            Message = M;

            Thread NewThread = new Thread(delegate ()
            {
                while (true)
                {
                    Thread.Sleep(Interval * 1000);

                    if (IsDone) { Run(); }
                }
            });

            NewThread.Start();
        }

        private void Run()
        {
            IsDone = false;

            if (Program.SQL.Connection.State != ConnectionState.Open) { Program.SQL.Connection.Open(); }

            using (SqlCommand Command = Program.SQL.Connection.CreateCommand())
            {
                List<String> OnlinePlayers = new List<String>();

                Command.CommandText = String.Format("SELECT sID FROM {0}..tLoggedInChars", Program.SQL.FilterDB);

                using (SqlDataReader Reader = Command.ExecuteReader())
                {
                    while (Reader.Read()) { OnlinePlayers.Add(Convert.ToString(Reader["sID"])); }

                    Reader.Close();
                }

                foreach (String OnlinePlayer in OnlinePlayers) { Program.SQL.PutMoneyInStorage(OnlinePlayer, MoneyToGive); }
            }

            using (var ClientPacket = new Packet(4, 8))
            {
                ClientPacket.PacketWriter.Write((Byte)0);
                ClientPacket.PacketWriter.Write("Server");
                ClientPacket.PacketWriter.Write(Message);

                Program.LocalClient.SendPacket(ClientPacket);
            }

            IsDone = true;
        }
    }
}
