using UnityEngine;
using System.Collections;

public class SlowMotionJump : MonoBehaviour
{
	public float TreeDistance		= 10;
	public float JumpDistance		= 20;
	public float ChargeTime			= 1.5f;
	public float BulletTime			= 0.01f;
	public float MaxJumpForce		= 100;

	private float m_line			= 0;
	private float m_min				= 0;
	private GameObject m_tree		= null;
	private GameObject m_player		= null;
	private Runner m_runner			= null;
	private bool m_start			= false;
	private bool m_counting			= false;
	private float m_elapsed			= 0;

	void Start ()
	{
		m_tree		= GameObject.Find( "WhackedTree" );
		m_line		= m_tree.transform.position.x - TreeDistance;
		m_min		= m_tree.transform.position.x - JumpDistance;
		m_player	= gameObject;
		m_runner	= m_player.GetComponent<Runner>();
	}

	void Update ()
	{
		if ( !m_start )
		{
			if ( Clicked() )
			{
				if ( m_player.transform.position.x >= m_min && m_player.transform.position.x <= m_line )
				{
					m_start = true;
					m_counting = true;
					Time.timeScale = BulletTime;
				}
				else if ( m_player.transform.position.x > m_line )
				{
					m_player.rigidbody.velocity = new Vector3(0,0,0);
					m_runner.Lose = true;
				}
			}
		}

		if ( m_start )
		{
			if ( m_counting )
			{
				if ( KeyDown() )
				{
					m_elapsed += Time.fixedDeltaTime;

					if ( m_elapsed >= ChargeTime )
					{
						StopCounting();
					}
				}
				else
				{
					StopCounting();
				}
			}

			if ( !m_counting )
			{
				float speed =  m_runner.Speed() /  m_runner.MaxSpeed;
				float force = ( ( m_elapsed * MaxJumpForce ) / ChargeTime );
				float total = force * speed;

				m_player.rigidbody.AddForce( Vector3.right * total );
				m_player.rigidbody.AddForce( Vector3.up * total );
			}
		}
	}

	void StopCounting()
	{
		m_counting = false;
		Time.timeScale = 1;
	}

	public bool Jumping()
	{
		return m_start;
	}

	bool KeyDown()
	{
		return Input.GetKey( KeyCode.Space ) || Input.GetMouseButton( 0 );
	}

	bool Clicked()
	{
		return Input.GetKeyDown( KeyCode.Space ) || Input.GetMouseButtonUp( 0 );
	}

	void OnGUI()
	{
		if ( m_start )
		{
			GUI.color = new Color( 0, 255, 0 );
			GUI.HorizontalSlider( new Rect( 32, 96, 568, 32 ), m_elapsed, 0, ChargeTime );
		}
	}

	void OnCollisionEnter( Collision _collider )
	{
		if ( _collider.gameObject.name.Contains( "obj_trunk" ) )
		{
			Debug.Log( "Velocity: " + m_player.rigidbody.velocity );
			m_player.rigidbody.velocity = new Vector3(0,0,0);
		}
	}
}
