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

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

        private Int32 Interval;

        #endregion

        private Boolean IsDone = true;

        public DBDuperTimer(Int32 I)
        {
            Interval = I;

            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())
                {
                    using (SqlCommand Command2 = Program.SQL.Connection.CreateCommand())
                    {
                        Command.CommandText = String.Format("SELECT nCharNo, nInt1 FROM {0}..tGameLog WHERE nType = '62' AND nInt2 = '2'", Program.Auth.ConfigValues["GameLogDB"]);

                        using (SqlDataReader Reader = Command.ExecuteReader())
                        {
                            Dictionary<Int32, Dictionary<UInt16, Int32>> QuestCompletes = new Dictionary<Int32, Dictionary<UInt16, Int32>>();

                            while (Reader.Read())
                            {
                                if (!QuestCompletes.ContainsKey(Convert.ToInt32(Reader["nCharNo"]))) { QuestCompletes.Add(Convert.ToInt32(Reader["nCharNo"]), new Dictionary<UInt16, Int32>()); }

                                if (!QuestCompletes[Convert.ToInt32(Reader["nCharNo"])].ContainsKey(Convert.ToUInt16(Reader["nInt1"]))) { QuestCompletes[Convert.ToInt32(Reader["nCharNo"])].Add(Convert.ToUInt16(Reader["nInt1"]), 0); }

                                QuestCompletes[Convert.ToInt32(Reader["nCharNo"])][Convert.ToUInt16(Reader["nInt1"])] += 1;
                            }

                            foreach (Int32 nCharNo in QuestCompletes.Keys)
                            {
                                foreach (UInt16 nQuestNo in QuestCompletes[nCharNo].Keys)
                                {
                                    if (QuestCompletes[nCharNo][nQuestNo] > 1)
                                    {
                                        if (!Program.SQL.tDupeDetectRowExists(nCharNo, "QUEST")) { Program.SQL.InserttDupeDetection(nCharNo, "QUEST"); }

                                        Program.SendConsoleText(ConsoleColor.Blue, "Quest duper detected. nCharNo {0}.", nCharNo);
                                    }
                                }
                            }
                        }

                        Command.CommandText = String.Format("SELECT nCharNo, nTargetID FROM {0}..tGameLog WHERE nType = '74'", Program.Auth.ConfigValues["GameLogDB"]);

                        using (SqlDataReader Reader = Command.ExecuteReader())
                        {
                            while (Reader.Read())
                            {
                                Boolean NoTrade = Convert.ToBoolean(Program.ItemInfo.Table.Rows.Cast<DataRow>().Where(ItemArray => Convert.ToUInt16(ItemArray.ItemArray[0]) == Convert.ToUInt16(Reader["nTargetID"])).FirstOrDefault().ItemArray[54]);

                                if (NoTrade && !Program.SQL.tDupeDetectRowExists(Convert.ToInt32(Reader["nCharNo"]), String.Format("TRADED NON TRADEABLE ITEM ({0})", Reader["nTargetID"])))
                                {
                                    Program.SQL.InserttDupeDetection(Convert.ToInt32(Reader["nCharNo"]), String.Format("TRADED NON TRADEABLE ITEM ({0})", Reader["nTargetID"]));

                                    Program.SendConsoleText(ConsoleColor.Blue, "Trade duper detected (non-tradeable item). nCharNo {0}. nTargetID: {1}.", Reader["nCharNo"], Reader["nTargetID"]);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception Error) { Program.SendConsoleText(ConsoleColor.Red, "Timers error - Database dupe checker\n{0}", Error.ToString()); }

            IsDone = true;
        }
    }
}
