using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Lobby : NetworkBehaviour
{
    [SyncVar]
    public int playerCount;
    [SyncVar]
    public string serverName;
    [SyncVar(hook = nameof(OnMetadataChanged))]
    public string serverMetadata;
    public string nextSceneName;
    void OnMetadataChanged(string oldValue, string newValue){
        SceneData.metadata = JsonUtility.FromJson<ServerMetadata>(newValue);
    }

    public Text lobbyNameText;
    public Text playerCountTxt;
    void Start()
    {
        DontDestroyOnLoad(gameObject);
        if(isServer){
            serverName = FindObjectOfType<LightReflectiveMirror.LightReflectiveMirrorTransport>().serverName;
            serverMetadata = FindObjectOfType<LightReflectiveMirror.LightReflectiveMirrorTransport>().extraServerData;
        }

        lobbyNameText.text = serverName;
        SceneData.metadata = JsonUtility.FromJson<ServerMetadata>(serverMetadata);
        playerCountTxt.text = playerCount+"/" + SceneData.metadata.maxPlayerCount;
    }

    // Update is called once per frame
    public int[] playlist = new int[2]{1,2};
    public int curSceneInd=0;
    void Update()
    {
        if(playerCountTxt!=null){
            playerCountTxt.text = playerCount + "/ " + SceneData.metadata.maxPlayerCount;
        }
        if(!isServer){
            return;
        }



        NetPlayer[] netPlayers = FindObjectsOfType<NetPlayer>();
        playerCount = netPlayers.Length;
        if(playerCount < 1){return;}
        bool allInside =true;
        foreach(NetPlayer netPlayer in netPlayers){
            if(!netPlayer.insideDoor){allInside = false;break;}
        }

        if(allInside){
            //Move onto next level
            if(curSceneInd < playlist.Length -1){
                curSceneInd++;
                nextSceneName = SceneManager.GetSceneByBuildIndex(playlist[curSceneInd]).name;
            }else{
                nextSceneName ="SampleScene";
                curSceneInd=0;
            }
            RpcNextLevel(playlist[curSceneInd]);
            changeScene(playlist[curSceneInd]);
        }
    }

    [ClientRpc]
    void RpcNextLevel(int levelName){
        changeScene(levelName);
    }

    void changeScene(int levelName){
        SceneData.localPlayer.GetComponent<PlayerController>().insideDoor=false;
        SceneData.localPlayer.GetComponent<NetPlayer>().CallChangeInsideDoor(false);

        LoadingScreen.instance.alreadyConnected=true;
        LoadingScreen.instance.sceneName=null;
        LoadingScreen.instance.sceneIndex = levelName;
        LoadingScreen.instance.load();
    }
}
