using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Threading;
using System.Collections.Generic;

public class Server : MonoBehaviour
{
	private Button button;
	private GameObject pupo;

	public static Position position = new Position();
	public static bool isInitialized = false;

	private Camera topCamera;

	private GameObject[] walls;

	private Canvas menu;
	private Canvas HUD;

	private AudioSource audioMenu;
	private AudioSource audioGame;

	void Awake()
	{
		button = GetComponent<Button>() as Button;
		button.onClick.AddListener(() => OnClickListener());

		pupo = GameObject.FindGameObjectWithTag("Player");
		
		topCamera = GameObject.FindGameObjectWithTag("top_camera").GetComponent<Camera>() as Camera;

		walls = GameObject.FindGameObjectsWithTag("wall");
		Debug.Log (walls.Length);

		menu = GameObject.FindGameObjectWithTag ("menu").GetComponent<Canvas> () as Canvas;
		HUD = GameObject.FindGameObjectWithTag ("hud").GetComponent<Canvas> () as Canvas;

		audioMenu = GameObject.FindGameObjectWithTag ("audio_menu").GetComponent<AudioSource> () as AudioSource;
		audioGame = GameObject.FindGameObjectWithTag ("audio_game").GetComponent<AudioSource> () as AudioSource;
	}

	void Update()
	{
		//Debug.Log("Server pos: " + position.x.ToString() + " " + position.y.ToString() + " " + position.z.ToString() + " " + isInitialized.ToString());
		//Debug.Log(position.rotationX.ToString() + " " + position.rotationY.ToString() + " " + position.rotationZ.ToString());
		if(isInitialized) 
		{
			pupo.transform.position = new Vector3(position.x, position.y, position.z);
			pupo.transform.rotation = Quaternion.Euler(position.rotationX, position.rotationY, position.rotationZ);
		}
	}

	private void OnClickListener()
	{
		menu.enabled = false;
		HUD.enabled = true;

		audioMenu.Stop ();
		audioGame.Play ();

		string s = GameObject.FindGameObjectWithTag("local_ip").GetComponent<Text>().text;
		Thread t = new Thread(()=>{MyTCPListener.Main(s);});
		t.Start();
	
		topCamera.camera.enabled = true;

		Destroy (pupo.GetComponent("MouseLook"));		
		Destroy (pupo.GetComponent("FPSInputController"));
		Destroy(pupo.GetComponent("CharacterMotor"));

		foreach(GameObject obj in walls)
			obj.GetComponent<MeshRenderer>().enabled = false;
	}
}



