using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Threading;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Client : MonoBehaviour
{
		private Button button;

		private Thread t;
		private GameObject player;
		private Position position = new Position ();
		private NetworkStream stream;

		private Camera mainCamera;

	private Canvas menu;
	private Canvas HUD;

	private AudioSource audioMenu;
	private AudioSource audioGame;

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

				player = GameObject.FindGameObjectWithTag ("Player");

				mainCamera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> () as Camera;

				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;
		}
		private float time = 0.02f;
		private float tmp = 0;
		void Update ()
		{
				if (t == null)
						return;
						
				if (tmp >= time) {
						position.x = player.transform.position.x;
						position.y = player.transform.position.y;
						position.z = player.transform.position.z;
	
						position.rotationY = player.transform.rotation.eulerAngles.y;
						position.rotationX = player.transform.rotation.eulerAngles.x;
						position.rotationZ = player.transform.rotation.eulerAngles.z;
	
						MyTCPListener.SendMessage (position.GetString (), stream);
			
						tmp = 0;
				}
				tmp += Time.deltaTime;

				
		}

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

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

		string s = GameObject.FindGameObjectWithTag("input_field").GetComponent<InputField>().text;
		Debug.Log (s);
				t = new Thread (() => {
						stream = MyTCPListener.Connect (s);});
				t.Start ();

				mainCamera.camera.enabled = true;
		Ghost.isEnabled = true;

		}
}
