import { Asset } from "cc";
import { SpriteFrame } from "cc";
import { Prefab, resources } from "cc";

export default class AB {
  async preLoad() {
    await this.loadPrefab("prefab/hall/Hall");
    await this.loadPrefab("prefab/hall/PageShop");
    await this.loadPrefab("prefab/hall/PageRank");
    await this.loadPrefab("prefab/hall/PagePlay");
    await this.loadPrefab("prefab/hall/PageWallet");

    // load all sprites from texture/hall folder
    let hallTextures = await this.loadDir("texture/hall", SpriteFrame);
    console.warn("hall textures loaded:", hallTextures.length);

    let rankTextures = await this.loadDir("texture/rank", SpriteFrame);
    console.warn("rank textures loaded:", rankTextures.length);
    let shopTextures = await this.loadDir("texture/shop", SpriteFrame);
    console.warn("shop textures loaded:", shopTextures.length);
    let playTextures = await this.loadDir("texture/play", SpriteFrame);
    console.warn("play textures loaded:", playTextures.length);

    let walletTextures = await this.loadDir("texture/wallet", SpriteFrame);
    console.warn("wallet textures loaded:", walletTextures.length);
    let commonTextures = await this.loadDir("texture/common", SpriteFrame);
    console.warn("common textures loaded:", commonTextures.length);

    await this.loadPrefab("prefab/layer/TipsLayer");

    return true;
  }

  async loadInLoading(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      resolve(true);
    });
  }

  loadRes(path: string, asset: typeof Asset): Promise<Asset> {
    return new Promise((resolve, reject) => {
      resources.load(path, asset, (err, asset) => {
        if (err) {
          reject(err);
        } else {
          resolve(asset);
        }
      });
    });
  }

  loadDir(path: string, asset: typeof Asset): Promise<Asset[]> {
    return new Promise((resolve, reject) => {
      resources.loadDir(path, asset, (err, assets) => {
        if (err) {
          reject(err);
        } else {
          resolve(assets);
        }
      });
    });
  }

  private static _ins: AB;

  public static get ins(): AB {
    return (AB._ins ??= new AB());
  }

  async loadPrefab(path: string): Promise<Prefab> {
    return new Promise((resolve, reject) => {
      resources.load(path, Prefab, (err, prefab) => {
        if (err) {
          reject(err);
        } else {
          resolve(prefab);
        }
      });
    });
  }

  async loadSpriteFrame(path: string): Promise<SpriteFrame> {
    let spPath = path + "/spriteFrame";
    let sp = await this.loadRes(spPath, SpriteFrame);
    return sp as SpriteFrame;
  }
}
