using UnityEngine;
using System.Collections;


[System.Serializable]
public class Boundary
{
	public float xMin, xMax, yMin, yMax;
}

public class Ship : MonoBehaviour 
{
	public Health health;
	public ShipManager shipManager;

	public GameObject playerDeath;

	public GameObject ship;
	public float speed;

	public Boundary boundary;

	public GameObject bullet;
	private float waitTilNextFire = 0.0f;
	public float fireRate = 5.0f;

	/*
	public Vector2 speed = new Vector2(50, 50);
	private Vector2 movement;
	*/
	
	void Start () 
	{
		health.setHealth(1);
		health.setLives(3);
	}


	void Update()
	{
		/*
		float inputX = Input.GetAxis("Horizontal");
		float inputY = Input.GetAxis("Vertical");
		movement = new Vector2(speed.x * inputX, speed.y * inputY);
		*/
		if(Input.GetButton("Up"))
		{
			ship.transform.Translate(0, speed * Time.deltaTime, 0);
		}
		if(Input.GetButton("Down"))
		{
			ship.transform.Translate(0, -speed * Time.deltaTime, 0);
		}

		if(Input.GetButton("Right"))
		{
			ship.transform.Translate(speed * Time.deltaTime, 0, 0);
		}
		if(Input.GetButton("Left"))
		{
			ship.transform.Translate(-speed * Time.deltaTime, 0, 0);
		}
	}


	void FixedUpdate()
	{
		/*
		rigidbody2D.velocity = movement;
		*/

		// Boundaries
		rigidbody2D.position = new Vector2(Mathf.Clamp(rigidbody2D.position.x, boundary.xMin, boundary.xMax), Mathf.Clamp(rigidbody2D.position.y, boundary.yMin, boundary.yMax));		
	}

	public void OnFire()
	{
		if (waitTilNextFire <= 0)
		{
			Instantiate(bullet, new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z), Quaternion.identity);
			waitTilNextFire = 1;
		}
		waitTilNextFire -= Time.deltaTime * fireRate;

	}


	void OnTriggerEnter2D(Collider2D other)
	{

		if(other.tag=="enemyBullet")
		{
			Instantiate(playerDeath, transform.position, transform.rotation);
			health.setHealth(health.getHealth()-1);
			Debug.Log("Health: "+health.getHealth());
			if(health.getHealth()==0)
			{
				health.setLives(health.getLives()-1);
				shipManager.startOnDeath();
			}
		}
	}

}
