import { Sprite } from "cc";
import { SpriteFrame, assetManager, AssetManager } from "cc";
import asset from "../../../extensions/ttttttttttttttt/@types/packages/engine/@types/editor-extends/manager/asset";
import { ModuleDef } from "../../scripts/ModuleDef";

export class AB {
  private static _inst: AB;
  public static get inst(): AB {
    if (!this._inst) {
      this._inst = new AB();
    }
    return this._inst;
  }

  public async setBundleBallImage(url: string, icon: Sprite) {
    let spriteFrame = await this.loadBundleSpriteFrame(ModuleDef.BALL, url);
    icon.spriteFrame = spriteFrame;
  }

  public async loadBundleSpriteFrame(bundleName: string, url: string) {
    let asset = await this._loadBundleAsset(bundleName, url + "/spriteFrame");
    return asset as SpriteFrame;
  }

  private async _loadBundleAsset(bundleName: string, url: string) {
    return new Promise((resolve, reject) => {
      assetManager.loadBundle(
        bundleName,
        (err, bundle: AssetManager.Bundle) => {
          if (bundle) {
            bundle.load(url, (err, asset) => {
              if (err) {
                reject(err);
              }
              resolve(asset);
            });
          } else {
            reject(new Error(`bundle ${bundleName} not found`));
          }
        }
      );
    });
  }
}
