using UnityEngine;
using System.Collections;

public class CollectableComponent : MonoBehaviour 
{
    private TM_Projectile myProjectile;

    public int iSquaresToGrant;
    public int iCirclesToGrant;
    public int iTrianglesToGrant;

    public float fTimeToAdd;
    public int iScoreToAdd;

    private Vector3 vFakeWorldPosition;
    private Vector3 vFakeInertia; 

    private float fTimeAlive = 0.0f;
    private float fArriveTime;
    private GameManager theGame;

    public AudioClip clip_onCollected;
    private AudioSource mySource;

    void Awake()
    {
        myProjectile = GetComponent<TM_Projectile>();
        theGame = GameObject.Find("GameManager").GetComponent<GameManager>();
        mySource = GetComponent<AudioSource>();
    }
    // Use this for initialization
    void Start()
    {
        myProjectile.AddOnHitOtherObjectFunction(OnCollectibleCollected);
    }

    // Use this for initialization
    public void OnCollectibleCollected(GameObject hitObject)
    {
        PlayerController pc = hitObject.GetComponent<PlayerController>();
        if (pc != null)
        {
            if (iSquaresToGrant != null)
                pc.AddShape(EShipForm.square, iSquaresToGrant);
            if (iCirclesToGrant != null)
                pc.AddShape(EShipForm.circle, iCirclesToGrant);
            if (iTrianglesToGrant != null)
                pc.AddShape(EShipForm.triangle, iTrianglesToGrant);

            if (fTimeToAdd != 0.0f)
            {
                theGame.AddTime(fTimeToAdd);
            }
            if (iScoreToAdd != 0)
            {
                theGame.AddScore(iScoreToAdd);
                //add score to score
            }
        }
        GameObject badcode = new GameObject();
        mySource = badcode.AddComponent<AudioSource>();
        Destroy(badcode,2.0f);

        TM_AudioManager.PlayClip(clip_onCollected, mySource);
    }

    public void LaunchCollectable(Vector3 vDirection, float fKickoffSpeed, float fTimeToGetToPlayer)
    {
        vFakeWorldPosition = transform.position;

        if (vDirection == Vector3.zero)
            vDirection = Random.insideUnitCircle.normalized;

        vFakeInertia = vDirection * fKickoffSpeed;
        fArriveTime = fTimeToGetToPlayer;
    }

	// Update is called once per frame
	void Update ()
	{
	    fTimeAlive += Time.deltaTime;
	    transform.position = Vector3.Lerp(vFakeWorldPosition, theGame.thePlayer.transform.position, fTimeAlive/fArriveTime);
	    vFakeWorldPosition += vFakeInertia*Time.deltaTime;
	}
}
