using UnityEngine;
using System.Collections;

public class Banana : MonoBehaviour
{
	public float BananaForceUp		= 500;
	public float BananaForceRight	= 1000;
	public float BananaSpeed		= 12;

	private GameObject m_obj		= null;
	private Vector3 m_init			= new Vector3();
	private float m_time			= 0;
	private bool m_delayedShot		= false;
	private bool m_wasVisible		= false;

	void Start ()
	{
		GameObject MyCamObj = GameObject.Find( "MainCamera" );

		if ( null != MyCamObj )
		{
			Hazards Haz = MyCamObj.GetComponent<Hazards>();
			WaterBonus Bon = MyCamObj.GetComponent<WaterBonus>();

			if ( null != Haz && null != Bon )
			{
				GameObject Obj = Haz.GetClosestHazard();
				GameObject Bonus = Bon.GetClosestBonus();

				if ( null != Obj )
				{
					Init();

					if ( null != Bonus )
					{
						if ( Obj.transform.position.x > Bonus.transform.position.x )
						{
							m_obj = Bonus;
							m_init = new Vector2( transform.position.x, transform.position.y );

							return;
						}
					}

					if (
						( Hazards.ModeEasy && MyCamObj.camera.transform.position.x > Obj.transform.position.x - 20 ) ||
						( !Hazards.ModeEasy && Obj.renderer.isVisible )
					)
					{
						if ( Hazards.ModeEasy && !Obj.renderer.isVisible )
						{
							if ( Projectile.Blocker == null )
							{
								m_delayedShot = true;
								Projectile.Blocker = gameObject;
							}
							else
							{
								DestroyObject( gameObject );
								return;
							}
						}
						
						m_obj = Obj;
						m_init = new Vector3( transform.position.x, transform.position.y, transform.position.z );
						m_time = Time.time;

						return;
					}
				}
			}
		}

		Init();
		rigidbody.AddForce( Vector3.up * BananaForceUp );
		rigidbody.AddForce( Vector3.right * BananaForceRight );
	}

	void Init()
	{
		GameObject Monkey = GameObject.Find( "PlayerWater" );

		if ( null != Monkey )
		{
			transform.position = new Vector3( Monkey.transform.position.x + 0.25f, Monkey.transform.position.y + 1, Monkey.transform.position.z + 1 );
			rigidbody.velocity = new Vector3( Monkey.rigidbody.velocity.x, Monkey.rigidbody.velocity.y, Monkey.rigidbody.velocity.z );
		}
	}

	void FixedUpdate ()
	{
		if ( m_delayedShot )
		{
			if ( m_obj.renderer != null && !m_obj.renderer.isVisible )
			{
				m_wasVisible = false;
				return;
			}
			else
			{
				if ( !m_wasVisible )
				{
					m_delayedShot		= false;

					if ( Projectile.Blocker == gameObject )
					{
						Projectile.Blocker = null;
					}
				}
			}
		}

		if ( !renderer.isVisible )
		{
			if ( Projectile.Blocker == gameObject )
			{
				Projectile.Blocker = null;
			}

			DestroyObject( gameObject );
			return;
		}

		if ( null != m_obj )
		{
			transform.position = Vector3.Lerp( m_init, m_obj.transform.position, ( Time.time - m_time ) * BananaSpeed );
		}
		else
		{
			transform.Rotate( Vector3.back * ( transform.localRotation.z + Time.deltaTime * 500 ) );
		}
	}
}
