using UnityEngine;
using System.Collections;

public class Coin : MonoBehaviour 
{
	
	public GameObject m_CoinMesh;
	public int		  m_ScoreValue = 250;
	public float      m_LifeTime   = 8.0f;
	
	Vector3 m_vBaseScale;
	Vector3 m_vBasePos;
	float   m_fLifeTime;
	float   m_fBounceAnim;
	
	// Use this for initialization
	void Start () 
	{
		m_fLifeTime = m_LifeTime;
		m_vBaseScale = this.transform.localScale;
		m_vBasePos   = m_CoinMesh.transform.localPosition;
		m_fBounceAnim = 1.0f;
	}
	
	// Update is called once per frame
	void Update () 
	{
		m_fLifeTime -= Time.deltaTime;		
		
		this.transform.Rotate(0.0f, Time.deltaTime*360.0f, 0.0f );
		
		if ( m_fBounceAnim > 0.0f )
		{
			m_fBounceAnim = Mathf.Max( m_fBounceAnim-Time.deltaTime*2.0f, 0.0f );
			float fOfs = Mathf.Sin( m_fBounceAnim*Mathf.PI ) * 15.0f;
			Vector3 vPos = m_vBasePos;
			vPos.y+=fOfs;
			m_CoinMesh.transform.localPosition = vPos;
		}
		
		if ( m_fLifeTime<0.5f )
		{
			if ( m_fLifeTime<=0.0f )
			{
				Object.Destroy( this.gameObject );				
			}
			else
			{
				Vector3 vScale = m_vBaseScale*(m_fLifeTime*2.0f);
				this.transform.localScale = vScale;
			}
			
		}
		
		if ( m_fBounceAnim<=0.0f )
		{
			GameController gc = GameController.GetInstance();
			if ( gc!=null )
			{
				GameObject p = gc.GetPlayer();
				if ( p!=null )
				{
					Vector3 vOfs = p.transform.position - transform.position;
					if ( vOfs.sqrMagnitude < 4.0f )
					{
						Object.Destroy( this.gameObject );
						gc.AddScore( m_ScoreValue, true, transform.position );
						gc.CollectCoin();						
					}
				}
			}
		}
	
	}
}
