import { props } from "../props";
const urls = [];
const picMap = {};
const posMap = {};
export default (parent, url, MAX_COL, MAX_ROW) => {
  if (picMap[url]) {
    const pics:any[] = picMap[url];
    for (const pic of pics) {
      parent.addChild(pic);
    }
    return [picMap[url], posMap[url]]
  }

  const W = props.W;
  const H = props.H;
  const GAP = props.GAP;

  const spr = [];
  const pos = []

  for (let row = 0; row < MAX_ROW; row++) {
    for (let col = 0; col < MAX_COL; col++) {

      const child = engine.Sprite.fromImage(url);
      spr.push(child);

      child.scaleX = 1 / MAX_COL;
      child.scaleY = 1 / MAX_ROW;
      parent.addChild(child);
      child.x = col * (W / MAX_COL + GAP);
      child.y = row * (H / MAX_ROW + GAP);
      pos.push([child.x, child.y]);
      // child.texture.addEventListener('update', () => {
      child.addEventListener(engine.Event.COMPLETE, () => {
        const uvs = new Float32Array([
          col / MAX_COL,
          row / MAX_ROW,
          (col + 1) / MAX_COL,
          row / MAX_ROW,
          (col + 1) / MAX_COL,
          (row + 1) / MAX_ROW,
          col / MAX_COL,
          (row + 1) / MAX_ROW,
        ]);

        child.uvs = uvs;
        // spr.push(child);
      });
    }
  }
  picMap[url] = spr.concat([]);
  posMap[url] = pos.concat([]);;
  // console.log(spr);
  return [spr, pos];
};
