// Copyright © 2017-2018 Atomic Software, LLC. All Rights Reserved.
// See LICENSE.md for full license information.

using Atom.Core;
using Atom.Core.Diagnostics;
using Atom.Core.Networking;
using Atom.Core.Networking.Messages.Structures.Local;

namespace Atom.WorldManagerServer
{
    internal class WorldManagerServer : Server
    {
        /// <summary>
        /// Listens for remote connections made to the server.
        /// </summary>
        public Listener RemoteListener { get; private set; }
        /// <summary>
        /// Listens for local connections made to the server.
        /// </summary>
        public Listener LocalListener { get; private set; }
        /// <summary>
        /// Represents the connection to the login server.
        /// </summary>
        public Client LoginServer { get; private set; }

        protected override void PerformStartActions()
        {
            Program.ShinePath = Config.GetString("DATA", "Path");
            Program.LoadSHNs();
            Program.LoadShineTables();

            RemoteListener = new Listener(Config.GetString("NET", "RemoteListenIP"), Config.GetInt32("NET", "RemoteListenPort"));
            LocalListener = new Listener(Config.GetString("NET", "LocalListenIP"), Config.GetInt32("NET", "LocalListenPort"));
            LoginServer = new Client(Config.GetString("NET", "LoginConnectIP"), Config.GetInt32("NET", "LoginConnectPort"));

            RegisterWorld();
        }

        private void RegisterWorld()
        {
            if (LoginServer == null)
            {
                Log.CriticalError("Could not register the world because the login server connection does not exist");
                return;
            }

            while (!LoginServer.IsConnected || LoginServer.EncryptionTable == null)
            {
                // just a wait block, ignore this.
            }

            new PROTO_NC_LOCAL_REGISTERWORLD_REQ(Config.GetByte("SERVER", "Number"), Config.GetString("SERVER", "Name"), Config.GetString("NET", "RemoteListenIP"), Config.GetInt32("NET", "RemoteListenPort")).SendLocal(LoginServer);
        }
    }
}
