using UnityEngine;
using System.Collections;

public class WaterBonus : MonoBehaviour
{
	public const int NUM_BONUSES			= 1;

	public Camera m_cam;

	public float DistanceBetweenBonuses		= 60;
	public float MinDistanceBetweenBonuses	= 20;
	public float BonusReductionRatio		= 0.95f;

	private float m_nextBonusX				= 560;

	private ArrayList m_bonuses;

	void Start()
	{
		m_bonuses = new ArrayList();
	}

	void Update()
	{
		if ( m_cam.transform.position.x + 60 > m_nextBonusX )
		{
			CreateBonus();
			NextBonus();
		}

		HazardsOffscreen();
	}

	void CreateBonus()
	{
		SpawnBonus( Random.Range( 1, NUM_BONUSES + 1 ) );
	}

	void SpawnBonus( int num )
	{
		GameObject Obj = Instantiate( Resources.Load( "obj_bonus_" + num.ToString() ) ) as GameObject;
		Obj.transform.position = new Vector3( m_nextBonusX + Random.Range( 0, DistanceBetweenBonuses ), Obj.transform.position.y, Obj.transform.position.z );

		m_bonuses.Add( Obj );
	}

	void CalcDistance()
	{
		DistanceBetweenBonuses *= BonusReductionRatio;

		if ( DistanceBetweenBonuses < MinDistanceBetweenBonuses )
		{
			DistanceBetweenBonuses = MinDistanceBetweenBonuses;
		}
	}

	void NextBonus()
	{
		CalcDistance();
		m_nextBonusX += DistanceBetweenBonuses;
	}

	void HazardsOffscreen()
	{
		if ( null != m_bonuses )
		{
			for ( int i = 0; i < m_bonuses.Count; i++ )
			{
				GameObject Obj = m_bonuses[i] as GameObject;

				if ( Obj.transform.position.x < m_cam.transform.position.x - 60 )
				{
					m_bonuses.RemoveAt( i );
					DestroyObject( Obj );
				}
			}
		}
	}

	public GameObject GetClosestBonus()
	{
		float dist = 999.0f;
		GameObject pivot = null;

		if ( null != m_bonuses )
		{
			for ( int i = 0; i < m_bonuses.Count; i++ )
			{
				GameObject Obj = m_bonuses[i] as GameObject;

				float tDist = ( Obj.transform.position.x - m_cam.transform.position.x );

				if ( tDist > 0 && tDist < dist )
				{
					pivot = m_bonuses[i] as GameObject;
					dist = tDist;
				}
			}

			return pivot as GameObject;
		}

		return null;
	}
}
