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

public class GameNetwork : NetworkManager
{
    public List<NetworkConnection> Connections = new List<NetworkConnection>();
	public bool isServer { get { return NetworkServer.connections.Count > 0; } } 

    public override void OnServerConnect(NetworkConnection conn)
    {
        base.OnServerConnect(conn);

        Connections.Add(conn);
        Debug.Log("client connected!");

        if(Connections.Count==2)
        {
			StartCoroutine (DelayStartGame());
        }
    }

	IEnumerator DelayStartGame()
	{
		// wait for server to be setup
		yield return new WaitForSeconds (1f);
		NetworkCommandRunner.CurrentCommandRunner.StartGame ();
	}

	IEnumerator DelayClientSetup(NetworkConnection conn)
	{
		// wait for player prefab to spawn
		while (NetworkCommandRunner.CurrentCommandRunner == null)
			yield return 0;
		
		NetworkCommandRunner.CurrentCommandRunner.myNetworkConnection = conn;
		if (!conn.isReady)
		{
			ClientScene.Ready (conn);
		}
	}

    public override void OnClientConnect(NetworkConnection conn)
    {
        base.OnClientConnect(conn);
		StartCoroutine (DelayClientSetup (conn));
		Debug.Log("Client connected. " + Network.connections.Length);
    }
}
