using UnityEngine;
using System.Collections;

public class fireball : MonoBehaviour {

    bool islerping = false;
    Vector3 starting;
    public Vector3 ending;
    public float percentage = 0;
    public float thrust = 25f;
    public float aimThrust = 25f;
    public GameObject playerRef;

    // Use this for initialization
    void Start () {
        Invoke("DestroyThis", 5f);
        islerping = true;
        starting = transform.position;
        ending = starting + ending;
        playerRef = GameObject.FindGameObjectWithTag("Player");

    }
	
	// Update is called once per frame
	void Update () {
        if (islerping)
        {
            LerpFireball();
        } else {
            aimingFire();
        }
	}

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            other.GetComponent<Rigidbody>().velocity = new Vector3(0, 5, 30);
            Destroy(gameObject);
        }

        if (other.gameObject.tag == "Backwall")
        {
            Destroy(gameObject);
        }
    }

    void LerpFireball()
    {
        gameObject.transform.localPosition = Vector3.Lerp(starting, ending, percentage);
        percentage += .02f;
        if (gameObject.transform.localPosition.y > (ending.y - .5f))
        {
            islerping = false;
            gameObject.GetComponent<Rigidbody>().AddForce(transform.forward * thrust);
        }
    }
    void aimingFire() {

        if (gameObject.transform.position.x > playerRef.transform.position.x + 0.2) {
            gameObject.GetComponent<Rigidbody>().AddForce(Vector3.right * (-aimThrust * 0.8f));
        }
        if (gameObject.transform.position.x < playerRef.transform.position.x - 0.2)
        {
            gameObject.GetComponent<Rigidbody>().AddForce(Vector3.right * aimThrust);
        }

        if (gameObject.transform.position.y > playerRef.transform.position.y)
        {
            gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up * (-aimThrust / 3));
        }
        if (gameObject.transform.position.y < playerRef.transform.position.y)
        {
            gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up * (aimThrust / 3));
        }

    }

    public void DestroyThis()
    {
        Destroy(gameObject);
    }
}
