using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;


namespace Multiplayer
{

    public class LoginManager
    {

        private ServerManager ServerManager;

        public LoginManager(ServerManager ServerManager)
        {
            this.ServerManager = ServerManager;
            RegisterHandles();
        }

        public void RegisterHandles()
        {
            ServerManager.Server.RegisterHandler(LoginMsgID.Name, OnPlayerLogin);
            ServerManager.Server.RegisterHandler(MsgType.Connect, OnConnect);
            ServerManager.Server.RegisterHandler(MsgType.Disconnect, OnDisconnect);
            ServerManager.Server.RegisterHandler(PlayerMsgID.GameStart, ClientStartsGame);
            ServerManager.Server.RegisterHandler(PlayerMsgID.Lobby, GoToLobby);
        }


        //Called when a player logs in
        public void OnPlayerLogin(NetworkMessage msg)
        {
            StringMsg stringMsg;
            if (!Utility.ReadMessage<StringMsg>(msg, out stringMsg))
                return;

            Debug.Log("Player login: " + stringMsg.String);

            if (ServerManager.AllPlayers.ContainsKey(stringMsg.ID))
            {
                Debug.Log(stringMsg.String + " already logged in");
                return;
            }

            Player newPlayer = new Player(msg.conn, stringMsg.String);
            ServerManager.AllPlayers.Add(newPlayer.ID, newPlayer);
        }


        private void OnConnect(NetworkMessage msg)
        {
            Debug.Log("New Connection: \n Address: " + msg.conn.address + "\n ID: " + msg.conn.connectionId);
            msg.conn.Send(LoginMsgID.QueryName, new PlayerMsg((byte)msg.conn.connectionId));
        }

        private void OnDisconnect(NetworkMessage msg)
        {
            if (ServerManager.AllPlayers.ContainsKey(msg.conn.connectionId))
            {
                Debug.Log(ServerManager.AllPlayers[msg.conn.connectionId].Name + "has disconnected.");
                ServerManager.AllPlayers.Remove(msg.conn.connectionId);
            }
            else
                Debug.Log("Unkown player has disconnected.");
        }

        private void ClientStartsGame(NetworkMessage msg)
        {
            StartGame();
        }

        private void StartGame()
        {
            foreach (Player player in ServerManager.AllPlayers.Values)
            {
                player.Connection.Send(LoginMsgID.Seed, new longMsg(player.ID, ServerManager.Seed));
                player.Connection.Send(PlayerMsgID.GameStart, new PlayerMsg(player.ID));
            }
        }



        private void GoToLobby(NetworkMessage msg)
        {
            foreach(Player player in ServerManager.AllPlayers.Values)
                player.Connection.Send(PlayerMsgID.Lobby, new PlayerMsg(player.ID));
        }
    }

}