using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour {
    public float speed = 10f;
    public float damage = 10f;
    public float damageCD = 0;
    public string targetTag = "Enemy";

    public bool isTimed = false;
    public bool destroyOnHit = true;
    public float detonationDelay = 1f;
    public GameObject detonationEffect;

    float cd;
    bool canDamage = true; 
	
	// Update is called once per frame
	void Update () {
        this.transform.position += this.transform.up * speed * Time.deltaTime;

        if (isTimed)
        {
            if (detonationDelay <= 0) Detonate();
            else detonationDelay -= Time.deltaTime;
        }

        cd -= Time.deltaTime;
        if (cd <= 0) canDamage = true;
        else canDamage = false;
	}

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.gameObject.tag == targetTag && canDamage)
        {
            if (targetTag == "Player") FindObjectOfType<GameManager>().DamagePlayer(damage);
            else other.GetComponent<Character>().Hit(damage);

            cd = damageCD;
            if (detonationEffect != null) Detonate();

            if (destroyOnHit)
                Destroy(this.gameObject);
        }
    }

    void Detonate()
    {
        speed = 0;
        GameObject post = (GameObject)Instantiate(detonationEffect, this.transform.position, this.transform.rotation);
        post.name = "detonation";
        if (destroyOnHit)
            Destroy(this.gameObject);    
    }
}
