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

public class Game : MonoBehaviour {
	public static Game instance;
	
	public Plane plane;
	public UI ui;

	int _checkpoints = 0;
	public int checkpoints {
		get { return _checkpoints; }
		set {
			if(_checkpoints != value) {
				_checkpoints = value;
				ui.Play(ui.sndCheckpoint);
				//TODO: Notify
			}
		}
	}

	//Config once initially, don't change mid-game
	public int pulsesPerBeat = 4;
	public float pulsePeriod = 1f;
	public float nextPulseTime { get; private set; }
	public float nextBeatTime {
		get { return nextPulseTime + nextBeatPulses * pulsePeriod; }
	}
	public float beatPeriod {
		get { return pulsePeriod * pulsesPerBeat; }
	}



	public int nextBeatPulses { get; private set; }
	public event Action<int> OnPreBeat = delegate {};			//absolute beats
	public event Action<int> OnBeat = delegate { };			//absolute beats
	public event Action<int, int> OnPrePulse = delegate {};	//absolute pulses, relative pulse
	public event Action<int, int> OnPulse = delegate {};	//absolute pulses, relative pulse
	public event Action<int, int> OnPostPulse = delegate {};	//absolute pulses, relative pulse
	
	int _beat = 0;
	int _pulse = 0;

	void Awake() {
		Debug.Assert(pulsePeriod > 0f);
		instance = this;
		ui = FindObjectOfType<UI>();
	}
	
	void Update () {
		nextPulseTime -= Time.deltaTime;
		while(nextPulseTime < 0f) {
			nextPulseTime += pulsePeriod;
			OnPrePulse(_pulse, _pulse%pulsesPerBeat);
			OnPulse(_pulse, _pulse%pulsesPerBeat);
			nextBeatPulses--;
			if(nextBeatPulses < 0) {
				nextBeatPulses = pulsesPerBeat;
				_beat++;
				OnPreBeat(_beat);
				OnBeat(_beat);
				ui.Play(ui.sndBeat, 0.5f);
			}
			OnPostPulse(_pulse, _pulse % pulsesPerBeat);
			_pulse++;

		}
	}
}
