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

public class Util
{
    public static GameObject Find(string name)
    {
        GameObject go = GameObject.Find(name);
        Debug.Assert(go != null, "Could not find object " + name);

        return go;
    }

    public static T Find<T>(string name)
    {
        GameObject go = Find(name);
        Debug.Assert(go.GetComponent<T>() != null, "Found object " + name + " but component " + typeof(T).Name + " is missing");

        return go.GetComponent<T>();
    }

    public static T FindChildInHierarchy<T>(Transform parent, string name) where T : Object
    {
        var go = FindChildInHierarchy(parent, name);
        return go ? go.GetComponent<T>() : null;
    }

    public static GameObject FindChildInHierarchy(Transform parent, string name, bool includeInactive = true)
    {
        Transform[] children = parent.GetComponentsInChildren<Transform>(includeInactive);
        foreach (Transform child in children)
        {
            if (child.name == name)
                return child.gameObject;
        }

        return null;
    }

    public static void RemoveAllChildren(GameObject go)
    {
        for (int i = go.transform.childCount - 1; i >= 0; --i)
        {
            var child = go.transform.GetChild(i).gameObject;
            Object.Destroy(child);
        }
    }

    /// <summary>
    /// Shuffles an IList with Fisher-Yates shuffle.
    /// </summary>
    public static void Shuffle<T>(IList<T> list)
    {
        for (int i = 0; i < list.Count; ++i)
        {
            int randomIdx = Random.Range(i, list.Count - 1);
            T tmp = list[i];
            list[i] = list[randomIdx];
            list[randomIdx] = tmp;
        }
    }

	public static T RandomElement<T>(T[] list)
	{
		return list[Random.Range(0, list.Length - 1)];
	}
}
