using UnityEngine;
using System.Collections;

public class ObjSpawner : MonoBehaviour
{
	public const float CLOUDS_DISTANCE		= 290.0f;
	public const int OBJ_RANDOM_NUM			= 2;

	public Camera m_cam;
	public WaterTerrainGenerator m_tg;

	public float RandomObjSpawnTime			= 15;
	private ArrayList m_objs				= null;
	private ArrayList m_clouds				= null;
	private float m_speed					= 50;

	private float m_objTotTime				= 0.0f;
	private float m_objNextTime				= 0.0f;

	void Start ()
	{
		m_objs = new ArrayList();
		m_clouds = new ArrayList();
	}

	void CreateRandomObj()
	{
		GameObject Obj = Instantiate( Resources.Load( "obj_random_" + Random.Range( 1, OBJ_RANDOM_NUM + 1 ) ) ) as GameObject;

		Obj.transform.position = new Vector3( m_tg.NextX() + Random.Range( 0.0f, WaterTerrainGenerator.BACK_SIZE ), Obj.transform.position.y, Obj.transform.position.z );

		m_clouds.Add( Obj );
	}

	void ObjectUpdate()
	{
		for ( int i = 0; i < m_objs.Count; i++ )
		{
			GameObject Obj = m_objs[i] as GameObject;

			Obj.transform.position = new Vector3(
				Obj.transform.position.x - ( Time.deltaTime * m_speed ),
				Obj.transform.position.y,
				Obj.transform.position.z
			);

			if ( Obj.transform.position.x < m_cam.transform.position.x - WaterTerrainGenerator.BACK_SIZE )
			{
				Debug.Log( "Removed obj because: " + Obj.transform.position.x.ToString() + " < " + ( m_cam.transform.position.x - WaterTerrainGenerator.BACK_SIZE ).ToString() );

				m_objs.RemoveAt( i );
				DestroyObject( Obj );
			}
		}

		m_objTotTime += Time.deltaTime;

		if ( m_objTotTime > m_objNextTime )
		{
			m_objTotTime = 0;
			m_objNextTime = RandomObjSpawnTime;

			CreateRandomObj();
		}
	}

	void Update () 
	{
		CloudsUpdate();
		ObjectUpdate();

	}

	public void SpawnClouds()
	{
		int num = Random.Range( 1, 5 );

		for ( int i = 0; i < num; i++ )
		{
			SpawnCloud();
		}
	}

	void CloudsUpdate()
	{
		if ( null == m_clouds )
		{
			m_clouds = new ArrayList();
		}

		for ( int i = 0; i < m_clouds.Count; i++ )
		{
			GameObject Obj = m_clouds[i] as GameObject;

			Obj.transform.position = new Vector3(
				Obj.transform.position.x - ( Time.deltaTime * m_speed ),
				Obj.transform.position.y,
				Obj.transform.position.z
			);

			if ( Obj.transform.position.x < m_cam.transform.position.x - WaterTerrainGenerator.BACK_SIZE )
			{
				m_clouds.RemoveAt( i );
				DestroyObject( Obj );
			}
		}
	}

	void SpawnCloud()
	{
		GameObject Obj = Instantiate( Resources.Load( "obj_cloud" ) ) as GameObject;

		Obj.transform.position = new Vector3( m_tg.NextX() + Random.Range( 0.0f, WaterTerrainGenerator.BACK_SIZE ), Random.Range( 0.0f, WaterTerrainGenerator.BACK_SIZE_H ), CLOUDS_DISTANCE );

		m_clouds.Add( Obj );
	}
}
