using UnityEngine;
using System.Collections;


public class Controller_Knob : Widget
	{

	//TrackManager trackManager;
	int value = 1;
	public int minValue = 1;
	public int maxValue = 4;
	public GameObject needle;
	public string symbol;
	float last_mouse_pos = 0;
	float accum_pos = 0;
	float max_accum = 50;
	Quaternion initial_rotation;
    int targetValue = -1;


	void OnMouseDown()
		{
		last_mouse_pos = Input.mousePosition.y;
		}
	void OnMouseUp()
		{
		}

	void OnMouseDrag()
		{
		float delta = Input.mousePosition.y - last_mouse_pos;
		last_mouse_pos = Input.mousePosition.y;
		accum_pos += delta;

		//Debug.Log (accum_pos);

		while( accum_pos > max_accum )
			{
			accum_pos -= max_accum;
			setValue( value + 1 );
			}

		while( accum_pos < - max_accum )
			{
			accum_pos += max_accum;
			setValue( value - 1 );
			}

		}

	new void Start ()
		{
		base.Start();
		//trackManager = GameObject.FindObjectOfType<TrackManager> ();
		initial_rotation = transform.rotation;
		isOutput = false;
		setValue (minValue);
		}

	void setValue( int v )
		{
		if( v > maxValue )
			v = maxValue;
		else if( v < 1 )
			v = 1;
		value = v;
		Vector3 newRotation = initial_rotation.eulerAngles;
		newRotation.z = + (v-minValue) * 105 / (maxValue-minValue) + 35;
		needle.transform.eulerAngles = newRotation;

        if (this.trackToReportTo != null)
        {
            if (this.targetValue != -1 && this.value == this.targetValue)
            {
                //when the target value is met, let the parent track know
                this.trackToReportTo.handleWidgetUpdate(this);
            }            
        }
        else
        {
            //Debug.Log("Reporting Invalid Widget Use in Controller_Knob.setValue");
            gameController.reportInvalidWidgetUse();
        }
	}

    public override void Update()
		{
		for( int v = minValue ; v <= maxValue ; v++ )
			{
			string k = v.ToString();
			if( Input.GetKeyDown(k) )
				setValue(v);
			}
		}

    override public void createTargetValue(Track listeningTrack)
    {
        this.trackToReportTo = listeningTrack;
        //make sure different than current
        int candidateValue = -1;
        while (candidateValue == this.value || candidateValue == -1)
        {
            candidateValue = rnd.Next(this.minValue, this.maxValue);
        }
        this.targetValue = candidateValue;
        this.isAvailable = false;
    }

    override public void clearTargetValue()
    {
        this.trackToReportTo = null;
        this.isAvailable = true;
    }

    override public string getTargetValueInstruction()
    {       
        return "turn " + this.symbol + " to " + this.targetValue;
    }

	}
