using UnityEngine;
using System.Collections;

public class BoulderMovementScript : MonoBehaviour {

	// Physics attributes
	public Rigidbody rigBody;
	private Vector2 startForce;
	private Vector2 jumpForce;
	private float jumpMultiplier;
    private GameObject collisionObject;

	// Game attributes
	private bool jumpHeld;
	public bool enemyKilled;
	public bool dead;
    bool grounded;

	// Object/Script References here
    // ....

	// Check for collision with terrain
    void OnCollisionStay(Collision collision)
    {
        if (collision.gameObject.tag == "Terrain")
        {
         //   Debug.Log("grounded");
            grounded = true;
        }
        
    }

    void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "Terrain")
        {
          //  Debug.Log("not grounded");
            grounded = false;
        }
    }

	// Use this for initialization
	void Start () 
	{
		// Initialise physics attributes
		rigBody = GetComponent<Rigidbody> ();
		startForce = new Vector2(3.0f, 0.0f); // The force the boulder is pushed off at.
		jumpForce = new Vector2(2.5f, 5.0f); // The default force that the boulder jumps at.
		jumpMultiplier = 1.0f; // The value increased the longer the mouse is held

		// Initialise game attributes
		jumpHeld = false;

		// Initialise Object/Script References here
        // ...
	}
	
	// Update is called once per frame
	void Update () 
	{

		if (transform.position.x < 0)
		{
			rigBody.AddForce(startForce);
		}

		if ((Input.GetMouseButton(0)) && (jumpHeld != true))
		{	// If left mouse is held down
			jumpHeld = true;
		}

		// Check for release, ensure boulder is in contact with the ground
		if ((jumpHeld == true) && (grounded) && (transform.position.x > 0))
		{
			if (Input.GetMouseButtonUp(0))
			{
			//	Debug.Log ("JUMP!");
				rigBody.AddForce((jumpForce * jumpMultiplier), ForceMode.Impulse);
				jumpHeld = false;
				jumpMultiplier = 1.0f;
			}
		}
		if ((jumpHeld ==  true) && (!grounded))
		{
			if (Input.GetMouseButtonUp (0))
			{
				jumpMultiplier = 1.0f;
				jumpHeld = false;
			}
		} 

		// Handle the jump multiplier
		if (jumpHeld == true)
		{
			jumpMultiplier += 0.025f; // per frame
		}
		if (jumpMultiplier > 2.5f)
		{
			jumpMultiplier = 2.5f;
		}

		// Check for death
		if (dead)
		{
			Dead();
		}

	}

	void Dead()
	{
		rigBody.velocity = rigBody.velocity * 0;
	}
}
