using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Bullet : MonoBehaviour 
{
	public static List<Bullet> s_AllBullets = new List<Bullet>();
	
	
	
	public float Speed 			= 10.0f;

	bool 		 m_bDead		=false;
	float		 m_fDestroytimer=0.7f;
	bool		 m_bRemove		= false;
	public bool  m_PlayerShot	= false;
	
	// Use this for initialization
	void Start () 
	{
		Bullet.Add( this );
	}
	
	// Update is called once per frame
	void Update () 
	{	
		if ( m_bRemove )
		{
			m_bRemove=false;
			Bullet.Remove( this );
		}
		
		float fTimeStep = Time.deltaTime;
		
		if ( m_bDead )
		{
			m_fDestroytimer-=fTimeStep;
			if ( m_fDestroytimer<=0.0f )
			{
				Object.Destroy(this.gameObject);
			}
		}
		else
		{
			Vector3 vPos = transform.position;
			Vector3 vNewPos = vPos + (transform.forward * Speed * fTimeStep);
			
			// Raycast against static colliders
			int iLevelColMask = 1<<8;
			
			Vector3 vDir = vNewPos-vPos;
			float fLen = vDir.magnitude;
			vDir.Normalize();			
			Ray r = new Ray( vPos, vDir );
			
			if ( Physics.Raycast( r, fLen, iLevelColMask ) )
			{
				// Bullet hit map edge
				m_bDead = true;				
				Bullet.Remove( this );
				TriggerImpactFX();
			}
			else
			{
				transform.position = vNewPos;
			}
			
			if ( !m_PlayerShot )
			{
				GameController gc = GameController.GetInstance();
				GameObject p = gc.GetPlayer();				
				
				if ( p!=null )
				{
					Vector3 vOfs = p.transform.localPosition - transform.position;
				
					if ( vOfs.sqrMagnitude < 1.0f )				
					{
						p.GetComponent<Player>().Dead();
					}
				}				
			}
		}
	}
	
	
	
	void TriggerImpactFX()
	{
		int iCount = transform.GetChildCount();
		
		for( int i=0; i<iCount; i++ )
		{
			GameObject c = transform.GetChild( i ).gameObject;
			c.SetActive( !c.activeInHierarchy );
		}
	}
	
	
	public void OnHitTarget()
	{
		m_bDead = true;				
		m_bRemove = true;
		TriggerImpactFX();
	}
	
	
	public static void Add(Bullet b)
	{
		s_AllBullets.Add(b);
	}
	
	public static void Remove(Bullet b)
	{
		if (s_AllBullets.Contains(b))
		{
			s_AllBullets.Remove(b);
		}
	}

	public static void Flush()
	{
		s_AllBullets.Clear();
	}
	
}
