class ResourceManager {
  constructor() {
    this.resources = new Map();
    this.loading = new Map();
  }

  load(src) {
    // 如果资源已加载，直接返回
    if (this.resources.has(src)) {
      return Promise.resolve(this.resources.get(src));
    }

    // 如果资源正在加载，返回相同的Promise
    if (this.loading.has(src)) {
      return this.loading.get(src);
    }

    // 创建新的加载Promise
    const promise = new Promise((resolve, reject) => {
      if (this.isImage(src)) {
        const img = new Image();
        img.onload = () => {
          this.resources.set(src, img);
          this.loading.delete(src);
          resolve(img);
        };
        img.onerror = (error) => {
          this.loading.delete(src);
          reject(error);
        };
        img.src = src;
      } else {
        // 其他资源类型处理
        reject(new Error(`Unsupported resource type: ${src}`));
      }
    });

    this.loading.set(src, promise);
    return promise;
  }

  isImage(src) {
    return /\.(jpeg|jpg|png|gif|svg|webp)$/i.test(src);
  }

  get(src) {
    return this.resources.get(src);
  }

  clear() {
    this.resources.clear();
    this.loading.clear();
  }
}

export default ResourceManager;
export { ResourceManager };