using UnityEngine;
using System.Collections.Generic;

public class SpacePitchHandler : MonoBehaviour {

    List<float> lasthits;
    public float pitch;
    public float playedpitch;
    public float amp;

    float last;

    void Awake() {
        last = Time.time;
        lasthits = new List<float>();
        amp = 0;
    }
	
	// Update is called once per frame
	void Update () {
        //print(lasthits.Count);
	    if (Input.GetKeyDown(KeyCode.Space) ||
            Input.GetKeyDown(KeyCode.A) ||
            Input.GetKeyDown(KeyCode.S) ||
            Input.GetKeyDown(KeyCode.D) ||
            Input.GetKeyDown(KeyCode.F) ||
            Input.GetKeyDown(KeyCode.G) ||
            Input.GetKeyDown(KeyCode.H) ||
            Input.GetKeyDown(KeyCode.J) ||
            Input.GetKeyDown(KeyCode.K) /*||
            (Time.time - last) > 0.125f*/) {
            last = Time.time;
            lasthits.Add(Time.realtimeSinceStartup);
        }
        if (lasthits.Count > 4 || lasthits.Count >= 1 && Time.realtimeSinceStartup - lasthits[0] > 1f)
            lasthits = lasthits.GetRange(1, lasthits.Count - 1);
        pitch = 0;
        if (lasthits.Count < 2) {
            amp = 0;
            return;
        }
        float persec = 0;
        float zz = 0;
        for (int i = 0; i < lasthits.Count-1; i++) {
            /*persec += Mathf.Sqrt(Mathf.Sqrt(lasthits.Count-i)) / (lasthits[i+1] - lasthits[i]);
            zz += Mathf.Sqrt(Mathf.Sqrt(lasthits.Count - i));*/
            persec += (lasthits.Count - i) / (lasthits[i + 1] - lasthits[i]);
            zz += (lasthits.Count - i);
        }
        persec = persec / zz;

         persec = (lasthits.Count - 1)/(lasthits[lasthits.Count-1] - lasthits[0]);
        pitch = persec * 110;

        //print(pitch);
        playedpitch = Tools.Note_To_Freq(Mathf.Round(Tools.Freq_To_Note(pitch)));
        //print(pitch);

        //print(lasthits.Count);
        amp = (lasthits.Count)/10f;
	}
}
