using UnityEngine;
using System;

public class AssetLoader {
#if UNITY_EDITOR
    private string assetBundleName;
    public AssetLoader(string assetBundleName){
        this.assetBundleName = assetBundleName.ToLower();
    }

    public T LoadAsset<T>(string assetName) where T : UnityEngine.Object {
        string[] assetPaths = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName.ToLower(), assetName); 
        if(assetPaths.Length > 0){
            return UnityEditor.AssetDatabase.LoadAssetAtPath<T>(assetPaths[0]);
        }else{
            return null;
        }
    }

#elif UNITY_ANDROID
    private string assetBundleName;
    public AssetLoader(string assetBundleName){
        this.assetBundleName = assetBundleName;
    }

    public T LoadAsset<T>(string assetName) where T : UnityEngine.Object {
        return Resources.Load<T>(string.Format("AssetBundle/{0}/{1}", assetBundleName, assetName));
    }

#elif UNITY_IOS
    private AssetBundle assetBundle;
    public AssetLoader(AssetBundle assetBundle){
        this.assetBundle = assetBundle;
    }

    public T LoadAsset<T>(string assetName) where T : UnityEngine.Object {
        if(assetBundle.Contains(assetName)){
            return assetBundle.LoadAsset<T>(assetName);
        }else{
            return null;
        }
    }
#endif

}

public class AssetBundleManager : SingletonMonoBehaviour<AssetBundleManager> {

    void Awake(){
        if(CheckInstance()) return ;
    }
    
    public void LoadAsset(string assetBundleName, Action<AssetLoader> action){
#if UNITY_EDITOR || UNITY_ANDROID
        action(new AssetLoader(assetBundleName));
#elif UNITY_IOS
        string path = Application.streamingAssetsPath + "/iOS/" + assetBundleName.ToLower();
        AssetBundle assetBundle = AssetBundle.LoadFromFile(path);
        action(new AssetLoader(assetBundle));
        assetBundle.Unload(false);
#endif
    }
}
