using System.Collections.Generic;
using UnityEngine;

namespace Ice {
  public static class ObjectUtil {
    public static void DestroyChildrenImmediate(GameObject parent) {
      DestroyChildrenImmediate(parent.transform);
    }

    public static void DestroyChildrenImmediate(Transform parent) {
      GameObject[] children = new GameObject[parent.childCount];
      for (int i = 0; i < parent.childCount; i++) {
        children[i] = parent.GetChild(i).gameObject;
      }
      foreach (var child in children) {
        Object.DestroyImmediate(child.gameObject);
      }
    }

    public static void DestroyChildren(GameObject parent) {
      DestroyChildren(parent.transform);
    }

    public static void DestroyChildren(Transform parent) {
      foreach (Transform child in parent) {
        Object.Destroy(child.gameObject);
      }
    }

    public static T CopyComponent<T>(T original, GameObject destination) where T : Component {
      System.Type type = original.GetType();
      var dst = destination.GetComponent(type) as T;
      if (!dst) dst = destination.AddComponent(type) as T;
      var fields = type.GetFields();
      foreach (var field in fields) {
        if (field.IsStatic) continue;
        field.SetValue(dst, field.GetValue(original));
      }
      var props = type.GetProperties();
      foreach (var prop in props) {
        if (!prop.CanWrite || !prop.CanWrite || prop.Name == "name") continue;
        prop.SetValue(dst, prop.GetValue(original, null), null);
      }
      return dst as T;
    }

    public static IList<GameObject> GetDirectChildren(Transform parent) {
      var ret = new List<GameObject>();
      foreach (Transform child in parent) {
        ret.Add(child.gameObject);
      }
      return ret;
    }

    public static void SetAllActive(IEnumerable<GameObject> objects, bool active) {
      foreach (var obj in objects) {
        obj.SetActive(active);
      }
    }
  }
} // namespace Ice
