import { resources } from "./resources";

export function preload(onProgress) {

  // 拿出所有图片
  const images = resources.reduce((list, item) => {
    if (item.image) {
      list.push(item.image)
    }
    if (item.thumb1) {
      list.push(item.thumb1)
    }
    if (item.thumb2) {
      list.push(item.thumb2)
    }

    return list;
  }, [])

  return new Promise((resolve, reject) => {
    const total = images.length;
    let cursor = 0;

    const callback = (e, isError) => {
      cursor += 1;
      onProgress(cursor / total);
      if (cursor >= total) {
        resolve(resources)
      }
    }

    for (let src of images) {
      const img = document.createElement('img');
      img.onload = e => callback(e, false);
      img.onerror = e => callback(e, true);
      img.src = src;
    }
  })
}
