﻿using UnityEngine;
using System.Collections;
using InControl;

public class Controls : MonoBehaviour {

	public Transform otherShip;

	//Camera Controls
	public KeyCode swapCameras;
	public Camera firstPersonCamera;
	public Camera firsPersonCockpitCamera;
	public Camera thirdPersonCamera;
	public Camera thirdPersonStatsCamera;

	//In Control Options
	public int deviceIndex;
	public bool invertedControls = true;

	GameObject objects;
	
	//Ship Controls
	float topSpeed = 10;
	float acceleration = 50;
	float turnSpeed = 1;
	Vector3 shipVelocity = Vector3.zero;
	float maxBoostTime = 3;
	float boostTimer = 0;
	bool usingBoost = false;
	public bool rolling = false;
	float coolDownTimeNeeded = 0.4f;
	float coolDownTimer = 0;
	float rollSpeed = 10;

	//Weapon Controls
	public int numRockets = 5;
	public GameObject bulletPrefab;
	public GameObject rocketPrefab;
	public AudioClip shotSound;
	public AudioClip rocketSound;
	float bulletSpeed = 20;
	float rocketSpeed = 20;
	

	// Use this for initialization
	void Start () {
		numRockets = 5;
		objects = GameObject.Find("Ships");
		//gameObject.GetComponent ("Health Text").GetComponent<TextMesh>().text = gameObject.GetComponent<LifeSystem> ().lifeBar.ToString ();
		//Debug.Log (GameObject.Find ("Rocket Text").GetComponent<TextMesh>().text);
		GameObject.Find ("P1 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P1 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<LifeSystem> ().lifeBar.ToString ();
		GameObject.Find ("P2 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P2 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<LifeSystem> ().lifeBar.ToString ();
	}
	
	// Update is called once per frame
	void Update () {

		GameObject.Find ("P1 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P1 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<LifeSystem> ().lifeBar.ToString ();
		GameObject.Find ("P2 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P2 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<LifeSystem> ().lifeBar.ToString ();

		//Restart Condition
		if (Input.GetKeyDown (KeyCode.Backspace)) {
			Application.LoadLevel("johnnys_game_scene");		
		}				

		if (Input.GetKeyDown(swapCameras)) {
			if (thirdPersonCamera.enabled == false){
				thirdPersonCamera.enabled = true;
				thirdPersonStatsCamera.enabled = true;
				firstPersonCamera.enabled = false;
				firsPersonCockpitCamera.enabled = false;
			}
			else {
				thirdPersonCamera.enabled = false;
				thirdPersonStatsCamera.enabled = false;
				firstPersonCamera.enabled = true;
				firsPersonCockpitCamera.enabled = true;
			}

		}

		rigidbody.velocity -= shipVelocity;





		if (InputManager.Devices.Count >= (deviceIndex + 1)) {

			// Left Joystick Controls
			if (InputManager.Devices[deviceIndex].LeftStickY.IsNotNull) {
				shipVelocity += transform.forward * InputManager.Devices[deviceIndex].LeftStickY.Value * (acceleration * Time.deltaTime);
			}
			if (InputManager.Devices[deviceIndex].LeftStickX.IsNotNull) {
				shipVelocity += transform.right * InputManager.Devices[deviceIndex].LeftStickX.Value * (acceleration * Time.deltaTime);
			}

			// Deceleration
			if (InputManager.Devices[deviceIndex].LeftStickY.IsNotNull && 
			    Mathf.Abs(InputManager.Devices[deviceIndex].LeftStickY.Value) < 0.05f &&
			    InputManager.Devices[deviceIndex].LeftStickX.IsNotNull && 
			    Mathf.Abs(InputManager.Devices[deviceIndex].LeftStickX.Value) < 0.05f) {

				if ((acceleration * Time.deltaTime) >= shipVelocity.magnitude) {
					shipVelocity = Vector3.zero;
				}
				else {
					shipVelocity += -shipVelocity.normalized * (acceleration * Time.deltaTime);
				}

			}
			// Clamping the ship velocity to top speed
			if (shipVelocity.magnitude > topSpeed) {
				shipVelocity = shipVelocity.normalized * topSpeed;
			}

			// Right Joystick Controls
			if (InputManager.Devices[deviceIndex].RightStickY.IsNotNull) {
				// Pitch Up (Down when inverted)
				if (invertedControls) {
					transform.Rotate(Vector3.right * InputManager.Devices[deviceIndex].RightStickY.Value * turnSpeed);
				}
				else {
					transform.Rotate(-Vector3.right * InputManager.Devices[deviceIndex].RightStickY.Value * turnSpeed);
				}
			}
			if (InputManager.Devices[deviceIndex].RightStickX.IsNotNull) {
				// Yaw Right (Left when inverted)
				if (invertedControls) {
					transform.Rotate(-Vector3.up * InputManager.Devices[deviceIndex].RightStickX.Value * turnSpeed);
				}
				else {
					transform.Rotate(Vector3.up * InputManager.Devices[deviceIndex].RightStickX.Value * turnSpeed);
				}
			}

			// Right Bumper Controls
			if (InputManager.Devices[deviceIndex].RightBumper.IsNotNull &&
			    InputManager.Devices[deviceIndex].RightBumper.WasPressed &&
			    !rolling) {
				// Roll
				StartCoroutine(barrelRoll());
			}
			
			
			// Left Bumper Controls
			if (InputManager.Devices[deviceIndex].LeftBumper.IsNotNull &&
			    InputManager.Devices[deviceIndex].LeftBumper.IsPressed) {
				// Boost
				boostTimer += Time.deltaTime;
				if (boostTimer > maxBoostTime) {
					usingBoost = false;
				}
				else {
					usingBoost = true;
				}
			}
			else {
				boostTimer -= Time.deltaTime;
				if (boostTimer < 0) {
					boostTimer = 0;
				}
				usingBoost = false;
			}
			
			
			// Right Trigger
			if (InputManager.Devices[deviceIndex].RightTrigger.IsNotNull &&
			    InputManager.Devices[deviceIndex].RightTrigger.IsPressed && 
			    (coolDownTimer == 0)) {
				
				coolDownTimer = coolDownTimeNeeded;

				//Shoot Bullet Audio
				audio.clip = shotSound;
				audio.Play ();


				//Ray Cast - Life System Calculation
				RaycastHit rayHit = new RaycastHit ();
				Ray ray = firstPersonCamera.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0f));

				if(Physics.Raycast (ray,out rayHit)){
					if (rayHit.collider.name.Contains("Ship Player") && rayHit.collider.GetComponent<Controls>().rolling != true  ){
						Debug.Log (rayHit.collider.name);
						rayHit.collider.GetComponent<LifeSystem>().lifeBar -= 1;
						Debug.Log(rayHit.collider.GetComponent<LifeSystem>().lifeBar);
					}
				}

				Debug.DrawRay (ray.origin, ray.direction * 1000, Color.yellow);

				//Screen Shake
				//firstPersonCamera.transform.localPosition = Random.insideUnitSphere * 2.0f;
		
				GameObject newBullet = (GameObject) Instantiate(bulletPrefab);
				newBullet.transform.parent = objects.transform;
				//newBullet.transform.eulerAngles = transform.eulerAngles;
				newBullet.transform.rotation  = transform.rotation;
				newBullet.transform.position = transform.position + transform.forward;
				newBullet.rigidbody.AddForce(newBullet.transform.forward * bulletSpeed, ForceMode.VelocityChange);
				//Delete After Period
				Destroy (newBullet.gameObject,3);

			}
			else {
				coolDownTimer -= Time.deltaTime;
				if (coolDownTimer < 0) {
					coolDownTimer = 0;
				}
			}



			// Left Trigger
			if (InputManager.Devices[deviceIndex].LeftTrigger.IsNotNull &&
			    InputManager.Devices[deviceIndex].LeftTrigger.WasPressed && (numRockets >0)) {

				numRockets --;

				//Shoot Rocket Audio
				audio.clip = rocketSound;
				audio.Play ();

				//Ray Cast - Life System Calculation
				RaycastHit rayHit = new RaycastHit ();
				Ray ray = firstPersonCamera.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0f));

				if(Physics.Raycast (ray,out rayHit)){
					if (rayHit.collider.name.Contains("Ship Player")){
						Debug.Log (rayHit.collider.name);
						rayHit.collider.GetComponent<LifeSystem>().lifeBar -= 5;
						Debug.Log(rayHit.collider.GetComponent<LifeSystem>().lifeBar);
					}
				}

				Debug.DrawRay (ray.origin, ray.direction * 1000, Color.red);

				//Screen Shake
				//firstPersonCamera.transform.localPosition = Random.insideUnitSphere * 1.0f * Mathf.Sin(Time.time * 100f);
				
				GameObject newRocket = (GameObject) Instantiate(rocketPrefab);
				newRocket.GetComponent<Follow>().target = otherShip;
				newRocket.transform.parent = objects.transform;
				newRocket.transform.rotation  = transform.rotation;
				newRocket.transform.position = transform.position + transform.forward;
				newRocket.rigidbody.AddForce(newRocket.transform.forward * rocketSpeed, ForceMode.VelocityChange);

				//Delete After Period
				Destroy (newRocket.gameObject,3);

			}

			if(InputManager.Devices[deviceIndex].RightStickButton.IsNotNull && InputManager.Devices[deviceIndex].RightStickButton.WasPressed){
				if (thirdPersonCamera.enabled == false){
					thirdPersonCamera.enabled = true;
					thirdPersonStatsCamera.enabled = true;
					firstPersonCamera.enabled = false;
					firsPersonCockpitCamera.enabled = false;
				}
				else {
					thirdPersonCamera.enabled = false;
					thirdPersonStatsCamera.enabled = false;
					firstPersonCamera.enabled = true;
					firsPersonCockpitCamera.enabled = true;
				}
			}



		}

		if (usingBoost) {
			rigidbody.velocity = shipVelocity * 2;
		}
		else {
			rigidbody.velocity = shipVelocity;
		}
		rigidbody.angularVelocity = new Vector3 ();
	}


	IEnumerator barrelRoll() {
		rolling = true;
		float totalRotation = 0;
		while (totalRotation < 360) {
			totalRotation += Vector3.forward.magnitude * rollSpeed;
			transform.Rotate(-Vector3.forward * rollSpeed);
			//thirdPersonCamera.transform.Rotate(Vector3.forward * rollSpeed);
			//thirdPersonStatsCamera.transform.Rotate(Vector3.forward * rollSpeed);
			yield return 0;
		}
		rolling = false;
	}
	
}

/*

using UnityEngine;
using System.Collections;
using InControl;

public class Controls : MonoBehaviour {
	
	public Transform otherShip;
	
	//Camera Controls
	public KeyCode swapCameras;
	public Camera firstPersonCamera;
	public Camera firsPersonCockpitCamera;
	public Camera thirdPersonCamera;
	public Camera thirdPersonStatsCamera;
	
	//In Control Options
	public int deviceIndex;
	public bool invertedControls = true;
	
	GameObject objects;
	
	//Ship Controls
	float topSpeed = 10;
	float stabilizationRate = 1;
	float acceleration = 50;
	float turnSpeed = 1;
	Vector3 shipVelocity = Vector3.zero;
	
	//Weapon Controls
	public int numRockets = 5;
	public GameObject bulletPrefab;
	public GameObject rocketPrefab;
	public AudioClip shotSound;
	public AudioClip rocketSound;
	float bulletSpeed = 20;
	float rocketSpeed = 20;
	
	
	// Use this for initialization
	void Start () {
		numRockets = 5;
		objects = GameObject.Find("Ships");
		//gameObject.GetComponent ("Health Text").GetComponent<TextMesh>().text = gameObject.GetComponent<LifeSystem> ().lifeBar.ToString ();
		//Debug.Log (GameObject.Find ("Rocket Text").GetComponent<TextMesh>().text);
		GameObject.Find ("P1 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P1 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<LifeSystem> ().lifeBar.ToString ();
		GameObject.Find ("P2 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P2 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<LifeSystem> ().lifeBar.ToString ();
	}
	
	// Update is called once per frame
	void Update () {
		
		GameObject.Find ("P1 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P1 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 1").GetComponent<LifeSystem> ().lifeBar.ToString ();
		GameObject.Find ("P2 Rocket Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<Controls>().numRockets.ToString();
		GameObject.Find ("P2 Health Text").GetComponent<TextMesh> ().text = GameObject.Find ("Ship Player 2").GetComponent<LifeSystem> ().lifeBar.ToString ();
		
		//Restart Condition
		if (Input.GetKeyDown (KeyCode.Backspace)) {
			Application.LoadLevel("johnnys_game_scene");		
		}				
		
		if (Input.GetKeyDown(swapCameras)) {
			if (thirdPersonCamera.enabled == false){
				thirdPersonCamera.enabled = true;
				thirdPersonStatsCamera.enabled = true;
				firstPersonCamera.enabled = false;
				firsPersonCockpitCamera.enabled = false;
			}
			else {
				thirdPersonCamera.enabled = false;
				thirdPersonStatsCamera.enabled = false;
				firstPersonCamera.enabled = true;
				firsPersonCockpitCamera.enabled = true;
			}
			
		}
		float newMagnitude;
		
		rigidbody.velocity -= shipVelocity;

		
		
		
		if (InputManager.Devices.Count >= (deviceIndex + 1)) {
			
			// Left Joystick Controls
			if (InputManager.Devices[deviceIndex].LeftStickY.IsNotNull) {
				shipVelocity += transform.forward * InputManager.Devices[deviceIndex].LeftStickY.Value * (acceleration * Time.deltaTime);
			}
			if (InputManager.Devices[deviceIndex].LeftStickX.IsNotNull) {
				shipVelocity += transform.right * InputManager.Devices[deviceIndex].LeftStickX.Value * (acceleration * Time.deltaTime);
			}
			
			// Deceleration
			if (InputManager.Devices[deviceIndex].LeftStickY.IsNotNull && 
			    Mathf.Abs(InputManager.Devices[deviceIndex].LeftStickY.Value) < 0.05f &&
			    InputManager.Devices[deviceIndex].LeftStickX.IsNotNull && 
			    Mathf.Abs(InputManager.Devices[deviceIndex].LeftStickX.Value) < 0.05f) {
				
				if ((acceleration * Time.deltaTime) >= shipVelocity.magnitude) {
					shipVelocity = Vector3.zero;
				}
				else {
					shipVelocity += -shipVelocity.normalized * (acceleration * Time.deltaTime);
				}
				
			}
			// Clamping the ship velocity to top speed
			if (shipVelocity.magnitude > topSpeed) {
				shipVelocity = shipVelocity.normalized * topSpeed;
			}
			
			// Right Joystick Controls
			if (InputManager.Devices[deviceIndex].RightStickY.IsNotNull) {
				// Pitch Up (Down when inverted)
				if (invertedControls) {
					transform.Rotate(Vector3.right * InputManager.Devices[deviceIndex].RightStickY.Value * turnSpeed);
				}
				else {
					transform.Rotate(-Vector3.right * InputManager.Devices[deviceIndex].RightStickY.Value * turnSpeed);
				}
			}
			if (InputManager.Devices[deviceIndex].RightStickX.IsNotNull) {
				// Yaw Right (Left when inverted)
				if (invertedControls) {
					transform.Rotate(-Vector3.up * InputManager.Devices[deviceIndex].RightStickX.Value * turnSpeed);
				}
				else {
					transform.Rotate(Vector3.up * InputManager.Devices[deviceIndex].RightStickX.Value * turnSpeed);
				}
			}
			
			// Right Trigger Controls
			if (InputManager.Devices[deviceIndex].RightTrigger.IsNotNull) {
				// Roll Right
				transform.Rotate(-Vector3.forward * InputManager.Devices[deviceIndex].RightTrigger.Value * turnSpeed);
			}
			
			
			// Left Trigger Controls
			if (InputManager.Devices[deviceIndex].LeftTrigger.IsNotNull) {
				// Roll Left
				transform.Rotate(Vector3.forward * InputManager.Devices[deviceIndex].LeftTrigger.Value * turnSpeed);
			}
			
			
			// Right Bumper
			if (InputManager.Devices[deviceIndex].RightBumper.IsNotNull &&
			    InputManager.Devices[deviceIndex].RightBumper.WasPressed) {
				
				//Shoot Bullet Audio
				audio.clip = shotSound;
				audio.Play ();
				
				
				//Ray Cast - Life System Calculation
				RaycastHit rayHit = new RaycastHit ();
				Ray ray = firstPersonCamera.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0f));
				
				if(Physics.Raycast (ray,out rayHit)){
					if (rayHit.collider.name.Contains("Ship Player")){
						Debug.Log (rayHit.collider.name);
						rayHit.collider.GetComponent<LifeSystem>().lifeBar -= 1;
						Debug.Log(rayHit.collider.GetComponent<LifeSystem>().lifeBar);
					}
				}
				
				Debug.DrawRay (ray.origin, ray.direction * 1000, Color.yellow);
				
				//Screen Shake
				//firstPersonCamera.transform.localPosition = Random.insideUnitSphere * 2.0f;
				
				GameObject newBullet = (GameObject) Instantiate(bulletPrefab);
				newBullet.transform.parent = objects.transform;
				//newBullet.transform.eulerAngles = transform.eulerAngles;
				newBullet.transform.rotation  = transform.rotation;
				newBullet.transform.position = transform.position + transform.forward;
				newBullet.rigidbody.AddForce(newBullet.transform.forward * bulletSpeed, ForceMode.VelocityChange);
				//Delete After Period
				Destroy (newBullet.gameObject,3);
				
				
			}
			
			// Left Bumper
			if (InputManager.Devices[deviceIndex].LeftBumper.IsNotNull &&
			    InputManager.Devices[deviceIndex].LeftBumper.WasPressed && (numRockets >0)) {
				
				numRockets --;
				
				//Shoot Rocket Audio
				audio.clip = rocketSound;
				audio.Play ();
				
				//Ray Cast - Life System Calculation
				RaycastHit rayHit = new RaycastHit ();
				Ray ray = firstPersonCamera.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0f));
				
				if(Physics.Raycast (ray,out rayHit)){
					if (rayHit.collider.name.Contains("Ship Player")){
						Debug.Log (rayHit.collider.name);
						rayHit.collider.GetComponent<LifeSystem>().lifeBar -= 5;
						Debug.Log(rayHit.collider.GetComponent<LifeSystem>().lifeBar);
					}
				}
				
				Debug.DrawRay (ray.origin, ray.direction * 1000, Color.red);
				
				//Screen Shake
				//firstPersonCamera.transform.localPosition = Random.insideUnitSphere * 1.0f * Mathf.Sin(Time.time * 100f);
				
				GameObject newRocket = (GameObject) Instantiate(rocketPrefab);
				newRocket.GetComponent<Follow>().target = otherShip;
				newRocket.transform.parent = objects.transform;
				newRocket.transform.rotation  = transform.rotation;
				newRocket.transform.position = transform.position + transform.forward;
				newRocket.rigidbody.AddForce(newRocket.transform.forward * rocketSpeed, ForceMode.VelocityChange);
				
				//Delete After Period
				Destroy (newRocket.gameObject,3);
				
			}
			
			if(InputManager.Devices[deviceIndex].RightStickButton.IsNotNull && InputManager.Devices[deviceIndex].RightStickButton.WasPressed){
				if (thirdPersonCamera.enabled == false){
					thirdPersonCamera.enabled = true;
					thirdPersonStatsCamera.enabled = true;
					firstPersonCamera.enabled = false;
					firsPersonCockpitCamera.enabled = false;
				}
				else {
					thirdPersonCamera.enabled = false;
					thirdPersonStatsCamera.enabled = false;
					firstPersonCamera.enabled = true;
					firsPersonCockpitCamera.enabled = true;
				}
			}
			
			
			
			// X Button Controls
			if (InputManager.Devices[deviceIndex].Action1.IsNotNull &&
			    InputManager.Devices[deviceIndex].Action1.IsPressed &&
			    InputManager.Devices[deviceIndex].Action1.WasReleased) {
				// Stabilize
				newMagnitude = rigidbody.angularVelocity.magnitude - (stabilizationRate * 0.1f); // 10 clicks = 1 sec of stabilization
				if (newMagnitude < 0) {
					newMagnitude = 0;
				}
				rigidbody.angularVelocity = rigidbody.angularVelocity.normalized * newMagnitude;
			}
			
		}
		
		rigidbody.velocity = shipVelocity;
		rigidbody.angularVelocity = new Vector3 ();
	}
}


*/
