using UnityEngine;
using System.Collections;

// notes
// 0 to 15
// precision 1

public class FreqSwingScript : FreqReactorScript {

    public float swing_frequency;

    public float curr_pow;
    public float max_swing_amplitude;

    public float rot_change_delta;

    private FreqOriginScript freq_source;

    int scoretogive;

    // Use this for initialization
    void Awake() {
        scoretogive = 100;

        RandomizeMe();
        freq_source = GameObject.FindGameObjectWithTag("Freq").GetComponent<FreqOriginScript>();
        if (resonance_frequency == 0) resonance_frequency = Tools.Note_To_Freq(resonance_note);
        else resonance_note = Tools.Freq_To_Note(resonance_frequency);
        curr_pow = 0;
    }

    void RandomizeMe() {
        resonance_note = Random.Range(3f, 10f); 
    }

    // Update is called once per frame
    void Update() {
        //print("ss" + freq_source.Freq().ToString());
        float pow = 0;
        if (freq_source.Amplitude() < 0.01f) { } // || freq_source.Freq() < 1) ;
        else {

            float[] fs = freq_source.Freqs();
            float bestnote = 10000;
            for (int i = 0; i < fs.Length; i++) {
                float nn = Tools.Freq_To_Note(fs[i]);
                if (Mathf.Abs(nn - resonance_note) < Mathf.Abs(bestnote - resonance_note)) bestnote = nn;
            }
            //print(bestnote);
            float curr_note = bestnote; //Tools.Freq_To_Note(freq_source.Freq());
            float diff = curr_note - resonance_note;
            //print(diff);
            pow = Mathf.Max(0, precision_needed -
                Mathf.Abs(diff)) * Mathf.Max(0, freq_source.Amplitude() / amplitude_needed);
            //print(pow);
            //print(freq_source.Amplitude());
            //print(amplitude_needed);
            if (pow > 1) pow = 1;
            
        }
        if (pow > curr_pow)
            curr_pow = Mathf.MoveTowards(curr_pow, pow, rot_change_delta);
        else
            curr_pow = Mathf.MoveTowards(curr_pow, pow, 0.1f*rot_change_delta);
        //print(curr_pow);
        GetComponent<Rigidbody2D>().rotation =
            max_swing_amplitude * curr_pow * Mathf.Sin(Mathf.PI * 2 * Time.time * swing_frequency);

        if (curr_pow > 0.25f) {
            if (scoretogive > 0) {
                ComboCenter.Instance.IncreaseScoreBy(1);
                scoretogive--;
            }
        }
    }
}
