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

public class LobbyUIController : MonoBehaviour
{
    [SerializeField]
    private ClientList Clients;

    [SerializeField]
    private string SceneToStart;

    [Header("UI Elements")]
    [SerializeField]
    private TextMeshProUGUI IPText;

    [SerializeField]
    private Transform Content;

    [SerializeField]
    private GameObject ClientTag;

    [SerializeField]
    private ServerObject Server;

    // Start is called before the first frame update
    void Start()
    {
        IPText.text = "Lobby - " + Networking.Utility.GetIP(Networking.Utility.ADDRESSFAM.IPv4);
    }

    private void OnEnable()
    {
        Clients.OnClientsChange += DisplayClients;
        DisplayClients(Clients.ConnectedClients);

        if (Server.server != null)
            Server.RegisterHandler(LoginProtocols.StartGame, RecieveStartMsg);
        else
            Debug.LogWarning("Server not started yet");
    }

    private void OnDisable()
    {
        Clients.OnClientsChange -= DisplayClients;

        if (Server.server != null)
            Server.UnregisterHandler(LoginProtocols.StartGame);
    }
		
    private void DisplayClients(List<ClientData> data)
    {
        //Debug.Log("Updating Connected Clients");
        foreach (Transform child in Content)
            if (child.gameObject != ClientTag)
                Destroy(child.gameObject);

        for (int i = 0; i < Clients.ConnectedClients.Count; i++)
        {
            ClientData client = Clients.ConnectedClients[i];

            GameObject clientObject = Instantiate(ClientTag, Content);
            TextMeshProUGUI clientText = clientObject.GetComponent<TextMeshProUGUI>();
			clientText.text = client.Name + " the " + client.characterAnimal;
            clientText.color = client.Color;

            Material materialInstance = clientText.fontMaterial;
            materialInstance.EnableKeyword(ShaderUtilities.Keyword_Underlay);
            materialInstance.SetColor("_UnderlayColor", new Color(0.2264151f, 0.2264151f, 0.2264151f, 1));
            materialInstance.SetFloat("_UnderlayOffsetX", 0.5f);
            materialInstance.SetFloat("_UnderlayOffsetY", -0.5f);

            clientObject.SetActive(true);
        }
    }

    public void OnClick_Back()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu Server");
    }

    public void OnClick_StartGame()
    {

#if UNITY_EDITOR
        UnityEngine.SceneManagement.SceneManager.LoadScene(SceneToStart);
#else
        if (Clients.ConnectedClients.Count >= 2 && Clients.ConnectedClients.Count <= 4){
			UnityEngine.SceneManagement.SceneManager.LoadScene(SceneToStart);
		}
#endif
    }

    public void RecieveStartMsg(UnityEngine.Networking.NetworkMessage msg)
    {
        OnClick_StartGame();
    }
}
