using UnityEngine;
using System.Collections;
using System.Linq;

public class Projectile : MonoBehaviour {


    public float Lifetime = 5.0f;
    private float fLifeRemaining;

    public float DamageOnHit;

    private SpriteRenderer m_mySpriteRenderer;
    public Sprite[] idleSprites;
    private Sprite[] currentSpriteCollection;
    private int iSpriteIndex;
    private float fAnimTimer;

    public Vector2 vDirection;
    public float fSpeed;

    public bool UsePhysicsToLaunch;
    public float PhysicsLaunchDrift;

    public bool ShouldCraterTerrain;
    public GameObject ParticleOnImpact;

	// Use this for initialization
	void Start () 
    {
        m_mySpriteRenderer = GetComponent<SpriteRenderer>();

        currentSpriteCollection = idleSprites;
        iSpriteIndex = 0;

        fLifeRemaining = Lifetime;
    }
	
	// Update is called once per frame
	public virtual void Update () 
    {
        UpdateSprites();

        UpdateMotion();

        fLifeRemaining -= Time.deltaTime;
        if (fLifeRemaining <= 0.0f)
            Destroy(gameObject);

        if( transform.position.x > 12 )
            Destroy(gameObject);
	}

    public virtual void UpdateMotion()
    {
        if (!UsePhysicsToLaunch)
        {
            Vector2 vPos = transform.position;
            vPos += vDirection*fSpeed*Time.deltaTime;
            transform.position = vPos;
        }
    }

    void UpdateSprites()
    {
        if (fAnimTimer > 0.0f)
            fAnimTimer -= Time.deltaTime;

        if (fAnimTimer > 0.0f)
            return;

        if (currentSpriteCollection == null)
            return;

        if (iSpriteIndex >= currentSpriteCollection.Count())
            iSpriteIndex = 0;

        m_mySpriteRenderer.sprite = currentSpriteCollection[iSpriteIndex];
        iSpriteIndex++;
        fAnimTimer = 0.1f;

        

    }

    void ProjectileImpact()
    {
        if (ParticleOnImpact != null)
        {
            GameObject go = Instantiate(ParticleOnImpact);
            go.transform.position = transform.position;
            Destroy(go,2.0f);
        }
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        //if enemy, 
        EnemyController ecs = coll.gameObject.GetComponent<EnemyController>();
        if (ecs != null)
        {
            ecs.TakeDamage(this);
            ProjectileImpact();
            Destroy(gameObject);
            return;
        }

        PlayerController pc = coll.gameObject.GetComponent<PlayerController>();
        if (pc != null)
        {
            pc.TakeDamage(DamageOnHit);
            ProjectileImpact();
            Destroy(gameObject);
            return;
        }


    }

    void OnTriggerEnter2D(Collider2D other)
    {
        //if enemy, 
        EnemyController ecs = other.gameObject.GetComponent<EnemyController>();
        if (ecs != null)
        {
            ecs.TakeDamage(this);
            ProjectileImpact();
            Destroy(gameObject);
            return;
        }
    }

}
