using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.SceneManagement;

public class GameLogicManager : MonoBehaviour {

    public PlayersRemainingDisplay playersRemainingDisplay; // has the number of players remaining 
    public RoundOverDisplay roundOverDisplay; // handles the game over screen stuff
    public StartMatch startMatch;
    public SpectatorController spectatorController;

    void Start() {

    }

    void Update() {
        if(PhotonNetwork.IsConnected && PhotonNetwork.CurrentRoom != null) {
            if (playersRemainingDisplay.GetRemainingPlayers() != -1 && playersRemainingDisplay.GetRemainingPlayers() <= 1 && !roundOverDisplay.IsRoundOver()) {
                roundOverDisplay.ShowWinner();
            }
            if(playersRemainingDisplay.GetRemainingPlayers() != -1 && 
                !spectatorController.IsCurrentlyPlaying() && 
                !spectatorController.IsCurrentlySpectatingPlayer() && 
                !startMatch.spawningPlayer) {

                spectatorController.SpectateAnyPlayer();
            }
        }
    }

    public void ReturnToLobby() {
        StartCoroutine(TotalDisconnect());
    }

    IEnumerator TotalDisconnect() {
        if (PhotonNetwork.InRoom) {
            PhotonNetwork.LeaveRoom();
        }

        PhotonNetwork.Disconnect();

        while (PhotonNetwork.IsConnected) {
            Debug.Log("waiting");
            yield return null;
        }

        SceneManager.LoadScene(0);
    }
}
