using System;
using System.Linq;
using System.Collections.Generic;

using FilterAPI;
using FilterAPI.Networking;
using FilterAPI.ItemExchange;
using FilterAPI.CustomCurrency;

using FilterCentral.LocalEnums;
using FilterCentral.LocalHandlers;
using FilterCentral.LocalNetworking;

namespace FilterCentral
{
    internal class Program
    {
        public static Authentication Auth;
        public static Database SQL;

        public static LocalHandlerLoader LocalHandlers;

        public static LocalClient LoginClient;
        public static LocalClient ManagerClient;
        public static Dictionary<String, LocalClient> ZoneClients = new Dictionary<String, LocalClient>();

        private static void Main(String[] Args)
        {
            Auth = new Authentication();

            Console.Title = String.Format("{0} Filter [{1}] :: Aeris.NET :: 2017/2018", Auth.ConfigValues["ServerName"], Properties.Resources.BuildDate);
            WriteLine(ConsoleColor.Green, "[Central] {0} Filter successfully booted up.", Auth.ConfigValues["ServerName"]);
            Console.ResetColor();

            SQL = new Database(Program.Auth);

            CurrencyLoader CustomCurrency = new CurrencyLoader(Auth);
            TokenLoader ItemExchange = new TokenLoader(Auth);

            if (!SQL.DatabaseExists(Auth.ConfigValues["CustomCurrencyDB"]))
            {
                WriteLine(ConsoleColor.Red, "[Central]: Database not found for custom currency. Please create a database called: {0} before starting the filter.", Auth.ConfigValues["CustomCurrencyDB"]);

                Console.ReadLine();

                Environment.Exit(0);
            }

            foreach (Currency Currency in CustomCurrency.Currencies)
            {
                WriteLine(ConsoleColor.Magenta, "[Central]: Checking if table exists in {0}: {1}.", Auth.ConfigValues["CustomCurrencyDB"], Currency.TableName);

                if (SQL.TableExists(Auth.ConfigValues["CustomCurrencyDB"], Currency.TableName)) { WriteLine(ConsoleColor.Green, "[Central]: Table found!"); }
                else
                {
                    WriteLine(ConsoleColor.Red, "[Central]: Could not find table. Creating...");

                    if (!Currency.IsCharacter) { SQL.CreateCCTable(Currency.TableName, "nUserNo"); }
                    else { SQL.CreateCCTable(Currency.TableName, "nCharNo"); }

                    WriteLine(ConsoleColor.Green, "[Central]: Created table for {0}.", Currency.CurrencyName);
                }

                if (Currency.HasMaximum)
                {
                    WriteLine(ConsoleColor.Magenta, "[Central]: Checking if obtained column exists in {0}: {1}.", Auth.ConfigValues["CustomCurrencyDB"], Currency.TableName);

                    if (SQL.TableHasColumn(Auth.ConfigValues["CustomCurrencyDB"], Currency.TableName, "Obtained")) { WriteLine(ConsoleColor.Green, "[Central]: Column found!"); }
                    else
                    {
                        WriteLine(ConsoleColor.Red, "[Central]: Could not find column. Adding...");

                        SQL.AddObtainedToTable(Currency.TableName);

                        WriteLine(ConsoleColor.Green, "[Central]: Added obtained column for {0}.", Currency.CurrencyName);
                    }
                }

                if ((CustomCurrency.CurrencyItemIDs.Where(CurrencyID => CurrencyID.CurrencyID == Currency.CurrencyID).FirstOrDefault()) == null)
                {
                    WriteLine(ConsoleColor.Red, "[Central]: No items could be found for currency: {0}. Please fix this before starting the filter.", Currency.CurrencyName);

                    Console.ReadLine();

                    Environment.Exit(0);
                }
            }

            foreach (Token Token in ItemExchange.TokenInfo)
            {
                WriteLine(ConsoleColor.Magenta, "[Central]: Checking if table exists in {0}: {1}.", Auth.ConfigValues["CustomCurrencyDB"], Token.TableName);

                if (SQL.TableExists(Auth.ConfigValues["CustomCurrencyDB"], Token.TableName)) { WriteLine(ConsoleColor.Green, "[Central]: Table found!"); }
                else
                {
                    WriteLine(ConsoleColor.Red, "[Central]: Could not find table. Creating...");

                    if (!Token.IsCharacter) { SQL.CreateCCTable(Token.TableName, "nUserNo"); }
                    else { SQL.CreateCCTable(Token.TableName, "nCharNo"); }

                    WriteLine(ConsoleColor.Green, "[Central]: Created table for {0}.", Token.TableName);
                }

                if ((ItemExchange.TokenItemIDs.Where(TokenID => TokenID.TokenID == Token.TokenID).FirstOrDefault()) == null)
                {
                    WriteLine(ConsoleColor.Red, "[Central]: No items could be found for currency: {0}. Please fix this before starting the filter.", Token.TokenName);

                    Console.ReadLine();

                    Environment.Exit(0);
                }
            }

            LocalListener LListen = new LocalListener();

            LocalHandlers = new LocalHandlerLoader();

            ReadCommand();
        }

        private static void ReadCommand()
        {
            String Text = Console.ReadLine();

            String[] TextSplit = Text.Split(' ');

            String Command = TextSplit[0].ToLower();

            if (Command == "reload")
            {
                using (var LocalPacket = new Packet(2, 4))
                {
                    foreach (LocalClient ZClient in Program.ZoneClients.Values) { ZClient.SendPacket(LocalPacket); }
                }

                WriteLine(ConsoleColor.Green, "Reload has been sent to the manager and {0} zones.", Program.ZoneClients.Values.Count());
            }

            ReadCommand();
        }

        public static void WriteLine(ConsoleColor Color, String Text, params Object[] Args)
        {
            String FormattedText = String.Format(Text, Args);

            Console.ForegroundColor = Color;
            Console.WriteLine(FormattedText);
        }
    }
}
