using UnityEngine;
using System.Collections;

public class NetworkManager : MonoBehaviour {
	
	private const string typeName = "TeamWoodChop";
	private const string gameName = "Room02";
	
	private HostData[] hostList;
	
	public GameObject playerPrefab;
	public Texture2D titleScreen;
	private Vector2 titleDist = new Vector2 (0.2f, 0.25f);
	
	void Start () {

	}
	
	void Update () {
		
	}
	
	//Starting a server
	private void StartServer()
	{
		Network.InitializeServer(12,25000,!Network.HavePublicAddress());
		MasterServer.RegisterHost(typeName, gameName);
	}
	
	void OnServerInitialized()
	{
		Debug.Log("Server Initialized");
		
		//instantiate player
		SpawnPlayer();
	}
	
	void OnGUI()
	{
		if(!Network.isClient && !Network.isServer)
		{
			//Title
			GUI.Label(new Rect((float)(Screen.width*(titleDist.x)),(float)(Screen.height*(titleDist.y)),1280,720), titleScreen);

			//Start Server
			if(GUI.Button(new Rect(100,100,250,100), "Start Server"))
				StartServer();
			
			//Refresh Host List
			if(GUI.Button(new Rect(100,250,250,100), "Refresh Host List"))
				RefreshHostList();
			
			if(hostList != null)
			{
				for (int i = 0; i < hostList.Length; i++)
				{
					if(GUI.Button(new Rect(400,100 + (110 * i), 300, 100), hostList[i].gameName))
						JoinServer(hostList[i]);
				}
			}
		}
	}
	
	
	//Joining a Server
	private void RefreshHostList()
	{
		MasterServer.RequestHostList(typeName);
	}
	
	void OnMasterServerEvent(MasterServerEvent msEvent)
	{
		if(msEvent == MasterServerEvent.HostListReceived)
			hostList = MasterServer.PollHostList();
	}
	
	private void JoinServer(HostData hostData)
	{
		Network.Connect(hostData);
	}
	
	void OnConnectedToServer()
	{
		Debug.Log("Server Joined");

		//instantiate player
		SpawnPlayer();
	}
	
	
	//Instantiate Players
	private void SpawnPlayer()
	{
		Network.Instantiate(playerPrefab, new Vector3(0f,10f,0f), Quaternion.identity, 0);
		//GameObject newPlayer = Network.Instantiate(playerPrefab, new Vector3(0f,10f,0f), Quaternion.identity, 0) as GameObject;
		//PlayerControl playercont = (PlayerControl) newPlayer.GetComponent<PlayerControl>();

		//playercont.runAtStart(newPlayer);
	}
}
