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

public class Harmonizer : MonoBehaviour {

	public float frequency;
	public float targetFrequency;
	public float difference = 0;

	public float disturbInterval;
	public float minInterval;
	public float maxInterval;

	public MidiControlNumbers controlNumbers;
	public int knobNumber;

	public GameObject redLight;
	public GameObject greenLight;

	public Reactor reactor;

	public AudioSource stabilized;
	public AudioSource destabilized;

	private bool stabilisedPlayed = true;

	// Use this for initialization
	void Start ()
	{

		targetFrequency = 0.5f;
		redLight.SetActive (false);
		greenLight.SetActive (true);
		disturbInterval = Random.Range (minInterval, maxInterval);
	}
		
	// Update is called once per frame
	void Update ()
	{
		if (controlNumbers.setupDone == false || reactor.meltdown == true)
			return;

		if (disturbInterval > 0)
			disturbInterval -= Time.deltaTime;

		else if (disturbInterval <= 0)
		{
			disturbInterval = Random.Range (minInterval, maxInterval);

			frequency = Random.Range (0.5f, 1.5f);
			frequency = Mathf.Clamp (frequency, 0.5f, 1.5f);

			targetFrequency = Random.Range (0.5f, 1.5f);
			targetFrequency = Mathf.Clamp (targetFrequency, 0.5f, 1.5f);

			destabilized.Play ();
			Invoke ("ResetStabilisedPlayed", 0.5f);
		}

		difference = Mathf.Abs (frequency - targetFrequency);

		if (difference < 0.1f)
		{
			redLight.SetActive (false);
			greenLight.SetActive (true);

			if (stabilized.isPlaying == false && stabilisedPlayed == false)
			{
				stabilized.PlayOneShot (stabilized.clip);
				stabilisedPlayed = true;
				Invoke ("AddSuccess", 0.2f);
			}

			reactor.temperature -= Time.deltaTime * reactor.heatingSpeed * 0.8f;
		}

		else if (difference > 0.1f)
		{
			redLight.SetActive (true);
			greenLight.SetActive (false);
			reactor.temperature += Time.deltaTime * reactor.heatingSpeed * difference * 3f;
		}

		frequency = MidiJack.MidiMaster.GetKnob (knobNumber) + 0.5f;
	}
		
	public void AddSuccess()
	{
		ScoreManager sm = FindObjectOfType<ScoreManager> ();
		sm.successess++;
	}

	void ResetStabilisedPlayed()
	{
		stabilisedPlayed = !stabilisedPlayed;
	}
}
