import AssetsBundleMgr from "../../utils/AssetsBundleMgr";
import FguiMgr from "../fgui/FguiMgr";

const { ccclass, menu, disallowMultiple, requireComponent } = cc._decorator;

/**
 * fguiload组件，自动管理资源的引用计数
 */
@ccclass
@disallowMultiple
@requireComponent(cc.Component)
export default class ResGComponent extends cc.Component {
	private _pkgName: string = null;
	LoadComp(bundleName: string, pkgName: string, resName: string, userClass: new () => fgui.GObject, onComplete: (comp: fairygui.GObject) => void) {
		AssetsBundleMgr.loadBundle(bundleName, (error, bundle: cc.AssetManager.Bundle) => {
			if (error) {
				return;
			}
			let pkg = fgui.UIPackage.getByName(pkgName);
			if (pkg) {
				if (this._pkgName != pkgName) {
					this.addDelayRelease(this._pkgName);
					FguiMgr.Instance.AddPkgCount(pkgName, 'ResGComponent');
				}
				this._pkgName = pkgName;
				let obj = pkg.createObject(resName, userClass);
				onComplete(obj);
			} else {
				fgui.UIPackage.loadPackage(bundle, pkgName, (error, pkg: fgui.UIPackage) => {
					if (error) {
						return;
					}
					if (this._pkgName != pkgName) {
						this.addDelayRelease(this._pkgName);
						FguiMgr.Instance.AddPkgCount(pkgName, 'ResGComponent');
					}
					this._pkgName = pkgName;
					let obj = pkg.createObject(resName, userClass);
					onComplete(obj);
				});
			}
		});
	}


	LoadComplete(url: string, scale: number, xFlip: boolean, yFlip: boolean) {

	}

	protected onDestroy(): void {
		this.resetRes();
	}

	/**
	 * 重置资源
	 */
	public resetRes(): void {
		if (this._pkgName) {
			// this.m_Asset.decRef();
			this.addDelayRelease(this._pkgName);
			this._pkgName = null;
		}
	}

	/** 5秒延迟释放资源 */
	protected addDelayRelease(pkgName: string) {
		setTimeout(() => {
			FguiMgr.Instance.DelPkgCount(pkgName, 'ResGComponent');
		}, 1000);
	}

}
