using UnityEngine;
using System.Collections;

// notes 5 to 25 set by candle spawner

public class FreqFallScript : FreqReactorScript {
    

    private FreqOriginScript freq_source;

    float health;

    // Use this for initialization
    void Awake() {

        health = 1;
        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);
    }
  

    // Update is called once per frame
    void Update() {
        float pow = 0;
        if (freq_source.Amplitude() < 0.01f /*|| freq_source.Freq() < 1*/) ;
        else {
            float[] fs = freq_source.Freqs();
            
            /*print(fs.Length);
            for(int i = 0; i < fs.Length; i++)
                print(fs[i]);*/
            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;
            //float curr_note = 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 > 0.25f) {
            float ss = (pow - 0.25f) / 0.25f * 0.05f;
            Vector2 newoffs = new Vector2(Random.Range(-ss, ss), Random.Range(-ss, ss));
            transform.position = transform.position + (Vector3)(newoffs - offs);
            offs = newoffs;
        }*/
        /*else {
            transform.position = transform.position - (Vector3)offs;
            offs = Vector2.zero;
        }*/
        if (pow >= 0.25f) {
            health -= 0.05f;
            if (health <= 0) {
                GetComponent<Rigidbody2D>().angularVelocity += Random.Range(5f,10f)*(Random.Range(0,2)*2-1);
                Destroy(gameObject.GetComponent<FreqSwingScript>());
                Destroy(this);
                Destroy(gameObject, 3);
            }
        }
        else {
            health += 0.06f;
            if (health > 1) health = 1;
        }
        //print(curr_pow);
    }
}
