using UnityEngine;
using System.Collections;

public class player2_controls : MonoBehaviour {

	public Animator animator;

	void Start () {	

	}	
	
	public float speed;
	public Vector2 jumpVector;
	public int health = 0;
	private int displayedHealth = 0;
	private bool updateHealth = false;
	private float curDirection = 1;
	public GameObject bullet;
	public GameObject heart;
	bool canJump = true;

	public string HorizontalBtn;

	public GameObject newConfetti;
	//Horizontal_P2

	
	
	void Update() {
		Vector2 velo = rigidbody2D.velocity;
		velo.x = Input.GetAxis (HorizontalBtn) * speed;
		rigidbody2D.velocity = velo;
		animator.SetFloat("Velocity",velo.magnitude);
		animator.SetBool ("Fall", !canJump);
		if (curDirection != Input.GetAxisRaw (HorizontalBtn))
			applyPlayerDirection (Input.GetAxisRaw (HorizontalBtn));

		if (displayedHealth != health) {
			updateHealth = true;
		}
		if (updateHealth)
			displayHealth (health);

		if (health == 0)
			death();
		
		if (Input.GetKey (KeyCode.W)){
			if (canJump == true){
				rigidbody2D.velocity = jumpVector;
				canJump = false;	
			}
		}
		
		//if (Input.GetKey (KeyCode.Space)){
		//shoot
		//GameObject bulletGO = Instantiate (bullet) as GameObject;
		//bulletGO.transform.posplayteition = transform.position;
		//}
	}

	private void displayHealth(int health){
		GameObject[] hearts = GameObject.FindGameObjectsWithTag("heartUI");
		foreach (GameObject desHeart in hearts)
			GameObject.Destroy (desHeart);

		for (int i=1; i<= health; i++) {
			GameObject heartCanister = Instantiate (heart) as GameObject;
			Vector3 heartPos = new Vector3 ((i * 0.033f), 0.95f, 0);
			heartCanister.transform.position = heartPos;
		}
		displayedHealth = health;
		updateHealth = false;
	}
	//Changes direction of sprite according to key pressed
	private void applyPlayerDirection(float moveHorizontal)
	{
		if (moveHorizontal != 0)
		{
			transform.Rotate(0,180,0);
			curDirection = moveHorizontal;
		}
	}

	private void Confettishoot(Vector3 target,float size){
		Debug.Log ("Creating Confetti");
		
		target.y += 1.5f;
			for (int i = 0; i <size; i++) {
				Instantiate (newConfetti, target, transform.rotation);
			}
	}

	private void death(){
		Vector3 spawnPos = new Vector3 (Random.Range (-20.0f, 20.0f), 15.0f, 0);
		health = 3;
		transform.position = spawnPos;
	}
	

	void OnCollisionEnter2D(Collision2D col){
		if (col.collider.tag == "ground")
			canJump = true;
		else if (col.collider.tag == "Player") {
			if(transform.position.y>col.transform.position.y){
				col.gameObject.GetComponent<PlayerControler>().health --;
				Confettishoot(col.gameObject.transform.position,20.0f);

				//health --;
				rigidbody2D.velocity = jumpVector;
				canJump = false;
			}
		}
	}


}