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

public enum NoteColor { RED, GREEN, BLUE };
public class NoteEvent : UnityEvent<NoteController> { }

public class NoteController : MonoBehaviour {
    public bool alreadyTriggered;
    public float speed;
    public NoteColor noteColor;
    public NoteEvent noteCollected, noteMissed;
    public GameObject explosionPrefab;

    private SpriteRenderer m_renderer;

    private void Awake() {
        m_renderer = GetComponent<SpriteRenderer>();
    }

    void Start () {
        alreadyTriggered = false;
    }

    public void init(){
        noteCollected = new NoteEvent();
        noteMissed = new NoteEvent();
    }

    void Update() {
        transform.position = new Vector3(
            transform.position.x - (speed * Time.deltaTime),
            transform.position.y,
            transform.position.z);

        if(transform.position.x < -40f) {
            noteMissed.Invoke(this);
        }
    }

    public void collect() {
        noteCollected.Invoke(this);
        SoundController.Instance.playSfx("feedback_target");
        StartCoroutine(shrink());
    }

    IEnumerator shrink() {
        speed = 0;
        GameObject explosion = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
        float elapsed = 0;
        while(elapsed < 1f) {
            transform.localScale = new Vector3(1- elapsed, 1 - elapsed, 0);
            yield return null;
            elapsed += Time.deltaTime * 3;
        }
        transform.localScale = Vector3.zero;
        yield return new WaitForSeconds(0.25f);
        Destroy(explosion);
        Destroy(gameObject);
    }

    public void setColor(NoteColor color) {
        noteColor = color;
        switch (noteColor) {
            case NoteColor.RED:
                m_renderer.color = ColorPalette.red;
                break;
            case NoteColor.GREEN:
                m_renderer.color = ColorPalette.green;
                break;
            case NoteColor.BLUE:
                m_renderer.color = ColorPalette.blue;
                break;
        }
    }
}
