using UnityEngine;
using System.Collections;

public class WaterTerrainGenerator : MonoBehaviour
{
	public Camera m_cam						= null;
	public ObjSpawner m_os					= null;

	public const float BACK_DISTANCE		= 300;

	public const float WP_SIZE				= 139.9f;
	public const float WP_SIZE_H			= WP_SIZE * 0.5f;

	public const float BACK_SIZE			= 500.0f;
	public const float BACK_SIZE_H			= BACK_SIZE * 0.5f;

	private ArrayList m_backs;
	private ArrayList m_planes;
	
	private float m_lastWpX					= 500.0f;
	private int m_planesNum					= 1;

	private float m_lastBackX				= 0.0f;
	//private int m_backsNum					= 1;

	public float NextX()
	{
		return m_lastBackX - BACK_SIZE;
	}

	void Start ()
	{
		m_planes = new ArrayList();
		m_backs = new ArrayList();


		BackgroundSpawn();
		WaterPlaneSpawn();
	}

	void Update()
	{
		BackgroundTrySpawn();
		BackgroundVisibility();

		WaterPlaneCheckVisibility();
		WaterPlaneTrySpawn();
	}

	void BackgroundSpawn()
	{
		//BackgroundSpawn( "obj_back_floor_" + Random.Range( 1, m_backsNum + 1 ) );
		BackgroundSpawn( "obj_back_floor" );
		m_os.SpawnClouds();
	}

	void BackgroundSpawn( string _backname )
	{
		GameObject Obj = Instantiate( Resources.Load( _backname ) ) as GameObject;
		Obj.transform.position = new Vector3( m_lastBackX, 250 - 50, BACK_DISTANCE );

		m_lastBackX += BACK_SIZE;

		m_backs.Add( Obj );
	}

	void BackgroundTrySpawn()
	{
		if ( m_cam.transform.position.x > m_lastBackX - BACK_SIZE - BACK_SIZE_H )
		{
			BackgroundSpawn();
		}
	}

	void BackgroundVisibility()
	{
		if ( null == m_backs )
		{
			m_backs = new ArrayList();
		}

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

			if ( null != back )
			{
				if ( back.transform.position.x < m_cam.transform.position.x - BACK_SIZE )
				{
					m_backs.RemoveAt( i );
					DestroyObject( back );
				}
			}
		}
	}

	void WaterPlaneSpawn()
	{
		WaterPlaneSpawn( "obj_water_plane_" + Random.Range( 1, m_planesNum + 1) );
	}

	void WaterPlaneSpawn( string _planename )
	{
		GameObject Obj = Instantiate( Resources.Load( _planename ) ) as GameObject;
		Obj.transform.position = new Vector3( m_lastWpX, 0, 0 );

		m_lastWpX += WP_SIZE;

		m_planes.Add( Obj );
	}

	void WaterPlaneTrySpawn()
	{
		if ( m_cam.transform.position.x > m_lastWpX - WP_SIZE - WP_SIZE_H )
		{
			WaterPlaneSpawn();
		}
	}

	void WaterPlaneCheckVisibility()
	{
		for ( int i = 0; i < m_planes.Count; i++ )
		{
			GameObject plane = m_planes[i] as GameObject;

			if ( null != plane )
			{
				if ( plane.transform.position.x < m_cam.transform.position.x - WP_SIZE  )
				{
					m_planes.RemoveAt( i );
					DestroyObject( plane );
				}
			}
		}
	}
}
