using UnityEngine;
using System.Collections;

public class Tucan : MonoBehaviour
{
	public float DistanceToTop		= 5;
	public float DistanceToEdge		= 3;
	public float TimeToAttack		= 2.5f;
	public float Speed				= 10;
	public float KickForce			= 250;

	private bool m_follow = false;
	private Camera m_cam;
	private float m_time;
	private bool m_hitDirLeft = false;
	private bool m_hitted	= false;

	public void Begin( bool _fromRigth )
	{
		m_hitDirLeft = _fromRigth;

		float diff = -DistanceToEdge;

		if ( _fromRigth )
		{
			diff = DistanceToEdge;
		}

		GameObject Came = GameObject.Find( "MainCamera" );
		m_cam = Came.GetComponent<Camera>();

		if ( null != m_cam )
		{
			transform.position = new Vector3 (
				m_cam.transform.position.x + diff,
				m_cam.transform.position.y + DistanceToTop,
				transform.position.z
			);
		}
	}
	
	void Update ()
	{
		if ( null == m_cam )
		{
			Debug.Log( "Null cam" );
			return;
		}

		if ( m_time < TimeToAttack )
		{
			if ( m_follow )
			{
				m_time += Time.deltaTime;

				transform.position = new Vector3( transform.position.x, m_cam.transform.position.y + DistanceToTop - 1, transform.position.z );
			}
			else
			{
				if ( transform.position.y > m_cam.transform.position.y + DistanceToTop - 1 )
				{
					transform.position = new Vector3( transform.position.x, transform.position.y - Time.deltaTime * 2, transform.position.z );
				}
				else
				{
					m_follow = true;
				}
			}
		}
		else
		{
			if ( !m_hitted )
			{
				GameObject Pla = GameObject.Find( "Player" );

				transform.position = new Vector3(
					transform.position.x + ( Time.deltaTime * Speed ) * ( Pla.transform.position.x - transform.position.x ),
					transform.position.y + ( Time.deltaTime * Speed ) * ( Pla.transform.position.y - transform.position.y ),
					transform.position.z
				);
			}
			else
			{
				transform.position = new Vector3(
					transform.position.x + ( Time.deltaTime * Speed ) * ( m_hitDirLeft ? -1 : 1 ),
					transform.position.y + ( Time.deltaTime * Speed ),
					transform.position.z
				);

				if ( !renderer.isVisible )
				{
					DestroyObject( gameObject );
				}
			}
		}
	}

	void OnTriggerEnter( Collider collisionInfo )
	{
		if ( m_hitted )
		{
			return;
		}

		if ( collisionInfo.collider.name == "Player" || collisionInfo.collider.name == "BodyBox" )
		{
			GameObject Play = GameObject.Find( "Player" );
			Player Pla = Play.GetComponent<Player>();

			if ( null != Pla )
			{
				if ( m_hitDirLeft )
				{
					Pla.PunchLeft( KickForce );
				}
				else
				{
					Pla.PunchRight( KickForce );
				}
			}

			m_hitted = true;
		}
		else if ( collisionInfo.name.Contains("obj_banana") )
		{
			DestroyObject( gameObject );
			DestroyObject( collisionInfo.gameObject );
		}
	}
}