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 GAbstateTimer
    {
        #region Timer Variables

        private Int32 Interval;
        private Int32 Duration;

        #endregion

        private Boolean IsDone = true;

        public GAbstateTimer(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
            {
                List<Int32> nCharNosInParty = Program.SQL.GettPartiesnCharNos();

                foreach (Int32 nCharNo in nCharNosInParty)
                {
                    String sMastersID;
                    List<String> sMembersIDs;

                    if (Program.SQL.GettPartiesFornCharNo(nCharNo, out sMastersID, out sMembersIDs))
                    {
                        foreach (DataRow Row in Program.PartyAbstates.Table.Rows.Cast<DataRow>().Where(ItemArray => Convert.ToByte(ItemArray.ItemArray[0]) == Convert.ToByte(sMembersIDs.Count + 1)))
                        {
                            using (var LocalPacket = new Packet(5, 11))
                            {
                                LocalPacket.PacketWriter.Write(Convert.ToString(Row.ItemArray[1]));
                                LocalPacket.PacketWriter.Write(Duration * 1000);
                                LocalPacket.PacketWriter.Write(Convert.ToByte(Row.ItemArray[2]));
                                LocalPacket.PacketWriter.Write(Program.SQL.GetsIDFromnCharNo(nCharNo));

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

            IsDone = true;
        }
    }
}
