using UnityEngine;
using System.Collections;

public class FreqSwing2Script : MonoBehaviour {

    public float resonance_note;
    public float resonance_frequency;
    public float precision_needed;
    public float amplitude_needed;
    
    public float swing_frequency;

    float curr_pow;
    public float max_swing_amplitude;

    private FreqOriginScript freq_source;
    float init_x;

    int dir;

	// Use this for initialization
	void Awake () {
        dir = 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);
        curr_pow = 0;
        init_x = transform.position.x;
	}

    // Update is called once per frame
    void Update () {
        //GetComponent<Rigidbody2D>().AddForce(Vector2.left);
        float pow = 0;
        if (freq_source.Amplitude() < 0.01f || freq_source.Freq() < 1) ;
        else {

            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);

            if (pow > 1) pow = 1;
                     
            
        }
        curr_pow = Mathf.Lerp(curr_pow, pow, 0.03f);
        //GetComponent<Rigidbody2D>().rotation =
        //    max_swing_amplitude * curr_pow * Mathf.Sin(Mathf.PI * 2 * Time.time * swing_frequency);
        /*float curroffs = max_swing_amplitude * curr_pow * Mathf.Sin(Mathf.PI * 2 * Time.time * swing_frequency);
        float wannabe = init_x + curroffs;*/
        if (curr_pow < 0.01f) {
        } else { 
            if (GetComponent<Rigidbody2D>().velocity.x <= 0 && Mathf.Abs(transform.position.x - init_x) < 0.1f) 
                GetComponent<Rigidbody2D>().AddForce(new Vector2(-curr_pow, 0));
            else if (GetComponent<Rigidbody2D>().velocity.x >= 0 && Mathf.Abs(transform.position.x - init_x) < 0.1f)
                GetComponent<Rigidbody2D>().AddForce(new Vector2(curr_pow, 0));
        }
        
    }
}

