using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Collectible : MonoBehaviour
{
    private CollectiblesTracker tracker;
    private Transform player;
    public Collider2D myCollider;

    public AnimationCurve scaleCurve;
    public float duration = 0.5f;
    public float smoothTime = .3f;

    public string type = "Easy";
    private bool collected = false;
    private Vector3 currentVelocity;

    // Start is called before the first frame update
    void Start()
    {
        // Find the collectibles tracker
        tracker = GameObject.FindGameObjectWithTag("CollectiblesTracker").GetComponent<CollectiblesTracker>();
        
        tracker.OnCollectibleAwakes(type);
    }

    private void OnTriggerEnter2D(Collider2D other) {
        if(other.tag == "Player" && !collected) {
            // Collected
            collected = true;
            tracker.OnCollectibleCollected(type);
            player = other.transform;
            myCollider.enabled = false;
            StartCoroutine(CollectProcedure());
        }
    }

    private IEnumerator CollectProcedure() {
        float time = Time.timeSinceLevelLoad;
        while(Time.timeSinceLevelLoad - time < duration) {
            float percent = (Time.timeSinceLevelLoad - time) / duration;
            transform.localScale = Vector3.one * scaleCurve.Evaluate(percent);
            transform.position = Vector3.SmoothDamp(transform.position, player.position, ref currentVelocity, smoothTime);
            yield return null;
        }
        Destroy(gameObject);
    }
}
