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

namespace Networking.Client
{

    public class ClientLoginManager : MonoBehaviour
    {
        #region Inspector Fields

        [Header("Connection Settings")]
        
        [SerializeField]
        [Tooltip("Server Address to Connect to")]
        private string ServerIP;

        [SerializeField]
        [Tooltip("Port to connect on")]
        private int Port;

        [SerializeField]
        [Tooltip("Try and connect on Play")]
        private bool StartClientOnAwake;

        [SerializeField]
        [Tooltip("Scene to load on connection")]
        private string LevelToLoad;

        [Header("Player Settings")]
        [SerializeField]
        [Tooltip("Player Name")]
        private string DisplayName;

        [SerializeField]
        [Tooltip("Player Color")]
        private Color PlayerColor;

        [Header("References")]
        [SerializeField]
        [Tooltip("Reference to actual Client")]
        protected ClientObject Client;

        #endregion Inspector Fields

        #region Private variables

        #endregion Private variables

        // Start is called before the first frame update
        private void Awake()
        {
            if (StartClientOnAwake)
                StartClient(ServerIP, Port);
        }

        public void OnEnable()
        {
            if (Client.isConnected)
                RegisterHandlers();
        }
        public void OnDisable()
        {
            Client.client.UnregisterHandler(LoginProtocols.RequestLoginDetails);
        }



        public void StartClient(string ipAddress, int port)
        {
            Client.Connect(ipAddress, port);

            RegisterHandlers();
        }

        public void RegisterHandlers()
        {
            Client.client.RegisterHandler(LoginProtocols.RequestLoginDetails, LoginRecieved);
            Client.client.RegisterHandler(LoginProtocols.LoginSuccess, LoginSucess);
            Client.client.RegisterHandler(LoginProtocols.LoginFail, LoginFail);
        }

        public void LoginRecieved(NetworkMessage msg)
        {
            Debug.Log("Connected to Server. Sending login details");
            Client.client.Send(LoginProtocols.SendingLoginDetails, new LoginProtocols.LoginMsg(DisplayName, PlayerColor));
        }

        public void LoginSucess(NetworkMessage msg)
        {
            Debug.Log("Log in successful");
            Client.UpdatePlayerDetails(DisplayName, PlayerColor);
            UnityEngine.SceneManagement.SceneManager.LoadScene(LevelToLoad);
        }

        public void LoginFail(NetworkMessage msg)
        {
            Debug.Log("Log in failed");
            Client.Stop();
        }

    }
}