using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System;

public class AssetBundleLoader : MonoBehaviour {

    public enum TargetAssetType {
        Image,
        SpriteRenderer,
    }

    [Serializable]
    public class AssetBundleLoadPack {
        public string assetName;
        public GameObject[] targetObjects = new GameObject[1];
        public TargetAssetType targetAssetType;
    }

    [Serializable]
    public class CallBackEvent : UnityEvent<Transform>{}
    [Serializable]
    public class AssetBundleParentPack {
        public Transform parent;
        public CallBackEvent callback;
    }
    [Serializable]
    public class AssetBundlePrefabPack {
        public string assetName;
        public AssetBundleParentPack[] parentPack;
    }

    [Serializable]
    public class AssetBundleInfo {
        public string assetBundlePath;
        public AssetBundleLoadPack[] loadPacks = new AssetBundleLoadPack[1];
        public AssetBundlePrefabPack[] prefabPacks = new AssetBundlePrefabPack[0];
    }

    public AssetBundleInfo[] assetBundleInfos = new AssetBundleInfo[1];

    void Awake(){
        foreach(AssetBundleInfo info in assetBundleInfos){
            AssetBundleManager.Instance.LoadAsset(info.assetBundlePath, assetLoader => {
                foreach(AssetBundleLoadPack pack in info.loadPacks){
                    Sprite sprite = assetLoader.LoadAsset<Sprite>(pack.assetName);
                    switch(pack.targetAssetType){
                    case TargetAssetType.Image:
                        foreach(GameObject targetObject in pack.targetObjects){
                            targetObject.GetComponent<Image>().sprite = sprite;
                        }
                        break;
                    case TargetAssetType.SpriteRenderer:
                        foreach(GameObject targetObject in pack.targetObjects){
                            targetObject.GetComponent<SpriteRenderer>().sprite = sprite;
                        }
                        break;
                    }
                }
                foreach(AssetBundlePrefabPack pack in info.prefabPacks){
                    Transform prefab = assetLoader.LoadAsset<GameObject>(pack.assetName).transform;
                    foreach(AssetBundleParentPack parentPack in pack.parentPack){
                        Transform transform = Instantiate<Transform>(prefab);
                        transform.name = transform.name.Replace("(Clone)", "");
                        transform.parent = parentPack.parent;
                        parentPack.callback.Invoke(transform);
                    }
                }
            });
        }
    }
}
