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

using FilterAPI.Networking;

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

        private Int32 Interval;
        private Int32 Duration;

        #endregion

        private Boolean IsDone = true;

        public PAbstateTimer(Int32 I, Int32 D)
        {
            Interval = I;
            Duration = D;

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

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

            NewThread.Start();
        }

        private void Run()
        {
            IsDone = false;

            try
            {
                using (SqlCommand Command = Program.SQL.Connection.CreateCommand())
                {
                    Command.CommandText = String.Format("SELECT * FROM {0}..tPermanentAbstates", Program.Auth.ConfigValues["FilterDB"]);

                    List<String> OnlinesIDs = Program.SQL.GetOnlinesIDs();

                    using (SqlDataReader Reader = Command.ExecuteReader())
                    {
                        while (Reader.Read())
                        {
                            String sID = Program.SQL.GetsIDFromnCharNo(Convert.ToInt32(Reader["nCharNo"]));

                            if (OnlinesIDs.Contains(sID))
                            {
                                using (var LocalPacket = new Packet(5, 11))
                                {
                                    LocalPacket.PacketWriter.Write(Convert.ToString(Reader["sIndex"]));
                                    LocalPacket.PacketWriter.Write(Duration * 1000);
                                    LocalPacket.PacketWriter.Write(Convert.ToByte(Reader["nEffect"]));
                                    LocalPacket.PacketWriter.Write(Program.SQL.GetsIDFromnCharNo(Convert.ToInt32(Reader["nCharNo"])));

                                    Program.LocalClient.SendPacket(LocalPacket);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception Error) { Program.SendConsoleText(ConsoleColor.Red, "Timers error - Permanent abstate giver\n{0}", Error.ToString()); }

            IsDone = true;
        }
    }
}
