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

namespace Multiplayer
{

    public class ClientLoginManager
    {

        private ClientManager ClientManager;

        public ClientLoginManager(ClientManager ClientManager)
        {
            this.ClientManager = ClientManager;
            RegisterHandlers();
        }

        private void RegisterHandlers()
        {
            ClientManager.Client.RegisterHandler(MsgType.Connect, OnConnected);
            ClientManager.Client.RegisterHandler(MsgType.Disconnect, OnDisconnected);
            ClientManager.Client.RegisterHandler(LoginMsgID.QueryName, OnRecieveID);
            ClientManager.Client.RegisterHandler(LoginMsgID.EnterLobby, StartLobby);
            ClientManager.Client.RegisterHandler(PlayerMsgID.GameStart, StartGame);
            ClientManager.Client.RegisterHandler(LoginMsgID.Seed, SetSeed);
        }

        private void OnConnected(NetworkMessage msg)
        {
            ClientManager.IsConnected = true;
            Debug.Log("Successfully connected to server");
        }

        private void OnDisconnected(NetworkMessage msg)
        {
            ClientManager.IsConnected = false;
            Debug.Log("Disconnected from Server");
        }

        private void OnRecieveID(NetworkMessage msg)
        {
            PlayerMsg playerMsg;
            if (!Utility.ReadMessage<PlayerMsg>(msg, out playerMsg))
                return;

            Debug.Log("Recieved ID from server: " + playerMsg.ID);

            ClientManager.ID = playerMsg.ID;
            ClientManager.SendMessage(LoginMsgID.Name, new StringMsg(ClientManager.ID, ClientManager.Name));
            StartLobby();
        }

        private void StartLobby(NetworkMessage msg)
        {
            StartLobby();
        }

        private void StartLobby()
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(ClientManager.LobbyScene);
        }

        private void StartGame(NetworkMessage msg)
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(ClientManager.GameScene);
        }

        private void SetSeed(NetworkMessage msg)
        {
            longMsg longMsg;
            if (!Utility.ReadMessage<longMsg>(msg, out longMsg))
                return;

            Random.InitState((int)longMsg.Long);
        }
    }

}