using UnityEngine;
using System.Collections;

public class Menu : MonoBehaviour {
	
	public GameObject playerAPrefab, playerBPrefab;
	public string serverIP = "localhost";
	public int serverPort = 34216;
	public int maxConnections = 2;
	
	void OnGUI ()
	{
		if (!Network.isClient && !Network.isServer)
			MenuGUI ();
	}
	
	void MenuGUI ()
	{
		if (!Network.isClient && !Network.isServer)
		{
			if (GUILayout.Button ("Start Server")) {
				Network.InitializeServer (maxConnections, serverPort, false);
			}
			if (GUILayout.Button ("Connect to server")) {
				Network.Connect (serverIP, serverPort);
			}
			serverIP = GUILayout.TextField (serverIP);
			
			GUILayout.Label ("My IP: " + Network.player.ipAddress);

		}
	}

	void CreatePlayer(bool playerA) {
		GameObject prefab, spawnPoint;
		if (playerA) {
			prefab = playerAPrefab;
			spawnPoint = GameObject.Find("SpawnPointA");
		}
		else {
			prefab = playerBPrefab;
			spawnPoint = GameObject.Find("SpawnPointB");
		}
		Network.Instantiate(prefab, spawnPoint.transform.position, prefab.transform.rotation, 0);
		Destroy(spawnPoint);
	}

	void OnConnectedToServer() {
		CreatePlayer (true);
		AssignCamera();
	}

	void OnPlayerConnected() {
		AssignCamera();
	}

	void AssignCamera() {
		StartCoroutine(AssignCameraDelayed());
	}

	IEnumerator AssignCameraDelayed() {
		yield return new WaitForSeconds(0.2f);
		Globals.playerA = (GameObject)GameObject.Find("PlayerA(Clone)");
		Globals.playerB = (GameObject)GameObject.Find("PlayerB(Clone)");
		
		if (Globals.playerA.networkView.isMine)
			Camera.main.GetComponent<FollowObject>().target = Globals.playerB.transform;
		else
			Camera.main.GetComponent<FollowObject>().target = Globals.playerA.transform;
	}
	
	void OnServerInitialized() {
		CreatePlayer(false);
		AssignCamera();
	}
}
