using LightReflectiveMirror;
using Mirror;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MainmenuController : MonoBehaviour
{
    public Text usernameTxt;
    [Header("Server List")]
    public Transform scrollParent;
    public GameObject serverRow;
    public float heightPerRow = 60;
    public int curSelected = 0;
    public LightReflectiveMirrorTransport _LRM;
    public Toggle isPublic;
    public InputField serverNameInput;
    public Slider maxPlayerCount;
    void Start()
    {
               
        _LRM = (LightReflectiveMirrorTransport)Transport.activeTransport;
        _LRM.serverListUpdated.AddListener(ServerListUpdate);
        _LRM.connectedToRelay.AddListener(refreshServers);
        usernameTxt.text = PlayerPrefs.GetString("username");
        serverNameInput.text = usernameTxt.text + "'s Server";
     //   refreshServers();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void OnDisable()
    {
        if (_LRM != null) { _LRM.serverListUpdated.RemoveListener(ServerListUpdate); }
    }

    public void refreshServers()
    {
        StartCoroutine(requestList());
    }

    IEnumerator requestList(){
        yield return new WaitForSeconds(1);
        if(_LRM == null){Debug.Log("WTF!");}
        _LRM.RequestServerList();
    }

    public void ServerListUpdate()
    {
       // 
        //clear all entries
        Debug.Log("it works");
        foreach(Transform t in scrollParent) { Destroy(t.gameObject); }
        for (int i =0; i < _LRM.relayServerList.Count; i++)
        {
            //int mapId = int.Parse(_LRM.relayServerList[i].serverName.Substring(0, 1));
                GameObject go = Instantiate(serverRow, scrollParent);
                go.transform.GetChild(0).GetComponent<Text>().text = _LRM.relayServerList[i].serverName;
                go.transform.GetChild(1).GetComponent<Text>().text = _LRM.relayServerList[i].currentPlayers + "/" + _LRM.relayServerList[i].maxPlayers;
                go.GetComponentInChildren<Button>().onClick.AddListener(() => { joinServer(_LRM.relayServerList[i-1].serverId.ToString()); });
                
                     
        }
        scrollParent.GetComponent<RectTransform>().sizeDelta = new Vector2(scrollParent.GetComponent<RectTransform>().sizeDelta.x, heightPerRow *(_LRM.relayServerList.Count+1));
    }

    public void selectServer(int id)
    {
        Debug.Log("Selected server :" + id);
        if(id < scrollParent.childCount-1) { return; }
        curSelected = id;
        foreach(Transform t in scrollParent.GetComponentsInChildren<Transform>())
        {
            if(t.GetComponent<Image>()!=null)t.GetComponent<Image>().color = serverRow.GetComponent<Image>().color;
        }
        scrollParent.GetChild(id).GetComponent<Image>().color = Color.grey;
    }

    public void joinServer()
    {
        LoadingScreen.instance.serverName = _LRM.relayServerList[curSelected].serverId.ToString();
       
        LoadingScreen.instance.load();
    }
    public void joinServer(string serverName)
    {
        LoadingScreen.instance.serverName = serverName;
        LoadingScreen.instance.sceneName= "SampleScene";
        LoadingScreen.instance.isHost=false;
        LoadingScreen.instance.alreadyConnected=false;

        LoadingScreen.instance.load();
    }

    public void hostClicked()
    {
        if (serverNameInput.text.Length > 3)
        {
            LoadingScreen.instance.serverName = serverNameInput.text;
            LoadingScreen.instance.sceneName= "SampleScene";            
            LoadingScreen.instance.isPublic = isPublic.isOn;
            LoadingScreen.instance.alreadyConnected=false;
            LoadingScreen.instance.isHost=true;
            ServerMetadata metadata = new ServerMetadata();
            metadata.maxPlayerCount = (int)maxPlayerCount.value;
            LoadingScreen.instance.serverMetadata = JsonUtility.ToJson(metadata);
            LoadingScreen.instance.load();
        }
    }
}


[System.Serializable]
public class ServerMetadata{
    public int maxPlayerCount;

    public ServerMetadata(){
        maxPlayerCount = 0;
    }
}