using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour {

    public LayerMask ignoreCollisionWith;
    public LayerMask damageCollisionWith;

    public float MaxLifetime;
    protected float fRemainingLifetime;
    public float Speed;

    public float LaunchBoost;

    //Real small, less than 1.0f
    public float ProjectileLaunchWiggle;

    public float DamageToDeal = 100.0f;

	// Use this for initialization
	void Start () 
    {
	
	}
	
	// Update is called once per frame
	public virtual void Update ()
	{
	    fRemainingLifetime -= Time.smoothDeltaTime;
        if( fRemainingLifetime < 0.0f )
            Destroy( gameObject );


        Vector3 vScale = transform.localScale;

	    if (GetComponent<Rigidbody2D>().velocity.x < 0.0f)
	        vScale.x = Mathf.Abs(vScale.x)*-1.0f;
	    else
	        vScale.x = Mathf.Abs(vScale.x);

        transform.localScale = vScale;
	}

    public virtual void Launch( Vector2 vDirection )
    {
        if (ProjectileLaunchWiggle > 0.0f)
        {
            vDirection.x += (-ProjectileLaunchWiggle + (ProjectileLaunchWiggle*2.0f*Random.value));
            vDirection.y += (-ProjectileLaunchWiggle + (ProjectileLaunchWiggle*2.0f*Random.value));
            vDirection.Normalize();
        }

        fRemainingLifetime = MaxLifetime;
        Rigidbody2D myBody = GetComponent<Rigidbody2D>();
        myBody.AddForce( vDirection * Speed );
        
        if( LaunchBoost != 0.0f )
            myBody.AddForce( Vector2.up * LaunchBoost);
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        //did we hit something we're supposed to ignore?
        if( ((1 << coll.gameObject.layer) & ignoreCollisionWith) != 0)
        {
            return;
        }

        BaseMans victim = coll.gameObject.GetComponent<BaseMans>();
        bool bShouldDestroy = true;
        if (victim != null)
        {
            bShouldDestroy = victim.EvaluateImpactWithProjectile(this);
        }

        if( bShouldDestroy )    
            Destroy(gameObject);
    }
}
