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

/// <summary>
/// Creates multiple copies of a template in a list.
/// </summary>
public class WidgetList : BaseBehaviour
{
	[SerializeField]
	private GameObject template;

	private List<GameObject> widgetList;

	private void Awake()
	{
		CheckIfSet(template);

		if (template != null)
			template.SetActive(false);

		widgetList = new List<GameObject>();
	}

	public GameObject AddWidget()
	{
		if (template == null) return null;

		var newWidget = Instantiate(template, transform);
		newWidget.SetActive(true);
		widgetList.Add(newWidget);

		return newWidget;
	}

	public T AddWidget<T>() where T : Component
	{
		var newWidget = AddWidget();
		if (newWidget == null) return null;

		T newWidgetComponent = newWidget.GetComponent<T>();

		if(newWidgetComponent == null)
		{
			LogError("Component of type {0} not found on template", typeof(T).Name);
			return null;
		}

		return newWidgetComponent;
	}

	public void RemoveAt(int widgetIndex)
	{
		if(widgetIndex < 0 || widgetIndex >= widgetList.Count)
		{
			LogError("Widget index {0} out of range", widgetIndex);
			return;
		}

		var widgetGameObject = widgetList[widgetIndex];
		RemoveWidget(widgetGameObject);
	}

	public void RemoveWidget<T>(T widgetComponent) where T : Component
	{
		if (widgetComponent == null) return;

		var widgetGameObject = widgetComponent.gameObject;
		RemoveWidget(widgetGameObject);
	}

	public void RemoveWidget(GameObject widgetGameObject)
	{
		if (widgetGameObject == null) return;

		if (widgetList.Remove(widgetGameObject))
			Object.DestroyObject(widgetGameObject);
	}

	/// <summary>
	/// Destroys all widgets
	/// </summary>
	public void ClearList()
	{
		for(int i = 0; i < widgetList.Count; i++)
		{
			if (widgetList[i] != null)
				Object.DestroyObject(widgetList[i]);
		}
		widgetList.Clear();
	}

}
