using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class WidgetManager : MonoBehaviour 
{
	private List<Widget> widgets;
	public GameObject controls; //set in editor

	//will run through all widgets and return one random "Input" type widget
	public Widget getRandomAvailableInputWidget()
	{
		List<Widget> availableWidgets = new List<Widget>();

		foreach (Widget w in widgets)
		{
			if (!w.isOutput && w.isAvailable)
			{
				availableWidgets.Add(w);
			}
		}

        if (availableWidgets.Count == 0) 
		{
			Debug.Log ("No available input widgets!");
			return null;
		}

		int randomIndex = Random.Range(0, availableWidgets.Count);
		availableWidgets[randomIndex].isAvailable = false;
		//Debug.Log ("Returning random input widget " + availableWidgets [randomIndex]);
		return availableWidgets [randomIndex];
	}

	//will run through all widgets and return one random "Output" type widget
	public Widget getRandomAvailableOutputWidget()
	{
		List<Widget> availableWidgets = new List<Widget>();
		
		foreach (Widget w in widgets)
		{
            //Debug.Log("Output Widget " + w);
			if (w.isOutput && w.isAvailable)
			{
				availableWidgets.Add(w);
			}
		}

        if (availableWidgets.Count == 0)
        {
            Debug.Log("No available output widgets!");
            return null;
        }
		int randomIndex = Random.Range (0, availableWidgets.Count);
		availableWidgets[randomIndex].isAvailable = false;
		//Debug.Log ("Returning random output widget " + availableWidgets [randomIndex]);
		return availableWidgets [randomIndex];
	}

	//will run through all widgets and return a List of active ones
	public List<Widget> getAvailableWidgets()
	{
		List<Widget> availableWidgets = new List<Widget>();

		foreach (Widget w in widgets)
		{
			if (w.isAvailable)
				availableWidgets.Add(w);
		}

		return availableWidgets;
	}

	// Use this for initialization
	void Start () 
	{
		widgets = new List<Widget>();
		widgets.AddRange(controls.GetComponentsInChildren<Widget>());
		Debug.Log("WidgetManager found " + widgets.Count + " widgets.");
	}
	
	// Update is called once per frame
	void Update () 
	{
	
	}
	
}