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

public class NoteCollider : MonoBehaviour
{
	public KeyCode[] keysToPress;

	private bool isChecking = false;

	//[HideInInspector]
	public int notesToCheckFor=-1;

	private int score;
	private bool tempBool = false;
	private bool pressedKey = false;

	private NoteController noteController;
	public NoteGenerator noteGenerator;

	public AudioClip correct;
	public AudioClip wrong;

	public void StartChecking() {
		score = 0;
		isChecking = true;
	}

	void OnTriggerEnter2D(Collider2D other)
    {
		tempBool = false;
		noteController = other.GetComponent<NoteController>();
    }

    void OnTriggerStay2D(Collider2D other){
		if (other.gameObject.tag=="MusicalNote") {
			CheckKeys();
		}
    }

	void OnTriggerExit2D(Collider2D other) {
		if (isChecking) {
			if (other.gameObject.tag == "MusicalNote") {
				other.gameObject.GetComponent<BoxCollider2D>().enabled = false;
				Destroy(other.gameObject);
				notesToCheckFor--;
				if (notesToCheckFor==0) {
					noteGenerator.DoneChecked(score);
				}
			}
		}
	}

	private void CheckKeys() {
		pressedKey = false;
		for (int x=0;x<keysToPress.Length;++x) {
			if (Input.GetKey(keysToPress[x])) {
				if (noteController!=null){
					if (x == (int)noteController.keyDirection) {
						++score;
						noteController.gameObject.GetComponent<BoxCollider2D>().enabled = false;
						Destroy(noteController.gameObject);
						notesToCheckFor--;
						if (notesToCheckFor == 0) {
							noteGenerator.DoneChecked(score);
						}
						AudioManager.Instance.Play(correct);
						return;
					}
				}
				pressedKey = true;
			}
		}
		if (pressedKey) {
			AudioManager.Instance.Play(wrong);
			noteController.gameObject.GetComponent<BoxCollider2D>().enabled = false;
			Destroy(noteController.gameObject);
			notesToCheckFor--;
			if (notesToCheckFor == 0) {
				noteGenerator.DoneChecked(score);
			}
		}
	}
}
