using Fiesta.Config;
using Fiesta.Players;
using Fiesta.Worlds;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Villain.Databases;
using Console = Villain.Output.Console;

namespace Login
{
	class Program
	{
		private static ServerInfo _serverInfo;
		private static ServerInfo.LoginServerInfo _loginServerInfo;

		private static DatabaseInfo _databaseInfo = new DatabaseInfo();

		static void Main(string[] args)
		{
			Console.Title = "Login";
			
			try
			{
				Console.WriteLine("Loading...", ConsoleColor.Green);

				Load();

				Console.WriteLine("Starting...", ConsoleColor.Green);

				Start();

				Console.WriteLine("Server Started!", ConsoleColor.Green);
			}
			catch (Exception exception)
			{
				Console.WriteLine($"Server threw an exception with the message: {exception.Message}", ConsoleColor.Red);

				Shutdown();
			}

			while (true)
			{
				switch (Console.ReadLine())
				{
					case "shutdown":
						Shutdown();
						break;
				}
			}
		}

		public static void Load()
		{
#if DEBUG
			_serverInfo = ServerInfo.Load(@"D:\Projects\Fiesta\Visual Studio\Fiesta\Servers\Emulator\Data\Config\ServerInfo.json");
			_databaseInfo = DatabaseInfo.Load(@"D:\Projects\Fiesta\Visual Studio\Fiesta\Servers\Emulator\Data\Config\DatabaseInfo.json");
#else
			_serverInfo = ServerInfo.Load(@"..\Data\Config\ServerInfo.json");
			_databaseInfo = DatabaseInfo.Load(@"..\Data\Config\DatabaseInfo.json");
#endif

			_loginServerInfo = _serverInfo.Login;

			DatabaseManager.OnClosed = OnDatabaseClosed;

			if (_databaseInfo.ContainsKey("Account"))
			{
				DatabaseInfo.Info accountDatabaseInfo = _databaseInfo["Account"];

				DatabaseManager.Add("Account", new SQLServer(accountDatabaseInfo.Host, accountDatabaseInfo.Database, accountDatabaseInfo.Username, accountDatabaseInfo.Password));
			}
			else
			{
				throw new Exception($"Unable to read database info for \"Account\"");
			}

			WorldManager.Load(_serverInfo.Worlds);
			PlayerManager.Load();
		}

		public static void Start()
		{
			WorldManager.Start(_loginServerInfo.Host, _loginServerInfo.Ports.Worlds);
			PlayerManager.Start(_loginServerInfo.Host, _loginServerInfo.Ports.Players);
		}

		public static void Shutdown()
		{
			// Tell all objects to unload and dispose

			Console.WriteLine("Server has shut down. Press any key to exit...", ConsoleColor.Yellow);
			Console.ReadLine();

			Environment.Exit(0);
		}

		private static void OnDatabaseClosed(string id)
		{
			Console.WriteLine("Server has shut down. Press any key to exit...", ConsoleColor.Yellow);

			Shutdown();
		}
	}
}