import { EResType, ResBaseAsset } from "./ResBaseAsset";

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

/**
 * 精灵组件，自动管理资源的引用计数
 */
@ccclass
@disallowMultiple
@requireComponent(cc.Sprite)
@menu('UI/ResSprite')
export default class ResSprite extends ResBaseAsset<cc.SpriteFrame> {
	private _sprite: cc.Sprite = null;
	get sprite() { return this._sprite || (this._sprite = this.node?.getComponent(cc.Sprite) || this.node?.addComponent(cc.Sprite)); }
	public get spriteFrame() { return this.sprite.spriteFrame; }
	protected readonly ResType: EResType = EResType.SpriteFrame;

	/**
	 * 通过 url 设置精灵 
	 * @param bundle 
	 * @param url 
	 * @param extraData 
	 * @param group 加载分组，默认为 ELoadingGroup.dft
	 * @param priority 优先级越小，越先加载，默认为 0
	 * @returns 
	 */
	setSpriteFrame(bundle: string, url: string, cb?: (asset: cc.SpriteFrame) => void) {
		this.loadAsset(bundle, url, cc.SpriteFrame, (asset: cc.SpriteFrame) => {
			if (asset && this.sprite && this.sprite.isValid) {
				this.sprite.spriteFrame = asset;
				cb && cb(asset);
			} else {
				cb && cb(null);
			}
		});
	}

	/**
	 * 不显示精灵（同时取消 spriteFrame 的设置）
	 */
	unsetSpriteFrame(): void {
		this.sprite.spriteFrame = null;
		this.resetRes();
	}

	/**
	 * 设置精灵的图片尺寸模式
	 * @param sizeMode 
	 */
	setSpriteSizeMode(sizeMode: cc.Sprite.SizeMode) {
		this.sprite.sizeMode = sizeMode as number;
	}
}
