using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

public static class MiscUtils {
    private static System.Random random = new System.Random((int)DateTime.Now.Ticks);

    public static void Shuffle<T>(this IList<T> list) {
        int n = list.Count;
        while (n > 1) {
            n--;
            int k = random.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }

    public static string RandomString(int size) {
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++) {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }

        return builder.ToString().ToLower();
    }

    public static void destroyByTag(string tagName) {
        if (!Application.isPlaying) {
            return;
        }

        GameObject[] objects = GameObject.FindGameObjectsWithTag(tagName);
        for (int i = 0; i < objects.Length; i++) {
            GameObject.DestroyImmediate(objects[i]);
        }
    }

    public static Transform FindChildRecursivly(this Transform transform, string name) {
        Transform result;

        if (transform.name == name) {
            return transform;
        }

        foreach (Transform child in transform) {
            result = child.FindChildRecursivly(name);

            if (result != null) {
                return result;
            }
        }

        return null;
    }

    public static void SetLayerRecursively(this GameObject obj, int layer) {
        obj.layer = layer;

        foreach (Transform child in obj.transform) {
            child.gameObject.SetLayerRecursively(layer);
        }
    }

    public static void SetX(this Transform trans, float x) {
        trans.position = new Vector3(x, trans.position.y, trans.position.z);
    }

    public static void SetY(this Transform trans, float y) {
        trans.position = new Vector3(trans.position.x, y, trans.position.z);
    }

    public static void SetZ(this Transform trans, float z) {
        trans.position = new Vector3(trans.position.x, trans.position.y, z);
    }

    public static void SetLocalX(this Transform trans, float x) {
        trans.localPosition = new Vector3(x, trans.localPosition.y, trans.localPosition.z);
    }

    public static void SetLocalY(this Transform trans, float y) {
        trans.localPosition = new Vector3(trans.localPosition.x, y, trans.localPosition.z);
    }

    public static void SetLocalZ(this Transform trans, float z) {
        trans.localPosition = new Vector3(trans.localPosition.x, trans.localPosition.y, z);
    }

    public static void Swap<T>(this IList<T> list, int indexA, int indexB) {
        T tmp = list[indexA];
        list[indexA] = list[indexB];
        list[indexB] = tmp;
    }
}
