import AudioMgr from "../AudioMgr/AudioMgr";

/**
 * 资源管理中心
 */
export default class AssetMgr {
	public static getSprNode(resName) {
		const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
		const node = new cc.Node();
		node.addComponent(cc.Sprite).spriteFrame = sf;
		return node;
	}

	public static getSpriteFrimeByUrl(url, cb) {
		cc.loader.load({ url }, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			if (cb) {
				cb(spriteFrame);
			}
		})
	}

	public static getSprNodeByUrl(url, cb) {
		const node = new cc.Node();
		const spr = node.addComponent(cc.Sprite);
		this.getSpriteFrimeByUrl(url, (sf) => {
			spr.spriteFrame = sf;
			if (cb) {
				cb(node);
			}
		})
	}

	private static callBack;

	public static playAudioByUrl(audio_url, cb = null) {
		if (audio_url) {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				// this.callBack && this.callBack();
				// this.callBack = cb;
				AudioMgr.stopAllEffect();
				AudioMgr.playEffect(audioClip, false, cb);
			});
		}
	}

	// 加载预制体文件
	public static loadBundlePrefab(abName: string, resPath: string): any {
		return new Promise((resolve, reject) => {
			cc.assetManager.loadBundle(abName, (err: Error | null, bundle: cc.AssetManager.Bundle) => {
				if (!err) {
					bundle.load(resPath, cc.Prefab, (err: Error | null, prefab: cc.Prefab) => {
						if (!err) {
							let node = cc.instantiate(prefab);
							resolve(node);
						} else {
							reject(null);
							console.warn(err);
						}
					});
				} else {
					reject(null);
					console.warn(err);
				}
			});
		})
	}

	//加载音频文件
	public static loadAudio(abName: string, resPath: string): Promise<cc.AudioClip> {
		return new Promise((resolve, reject) => {
			cc.assetManager.loadBundle(abName, (err: Error | null, bundle: cc.AssetManager.Bundle) => {
				if (!err) {
					bundle.load(resPath, cc.AudioClip, (err: Error | null, clip: cc.AudioClip) => {
						if (!err) {
							resolve(clip);
						} else {
							reject(null);
							console.warn(err);
						}
					});
				} else {
					reject(null);
					console.warn(err);
				}
			});
		})
	}

}
