var opacity = -1
var state = null

export async function process(inscription_ids) {
  let body = document.querySelector("body");
  body.style.height = "100vh";
  body.style.margin = "0";
  body.style.display = "flex";

  let promises = inscription_ids.map(
    (inscription_id) =>
      new Promise((resolver) => {
        let image = new Image();
        image.crossOrigin = "anonymous";
        image.onload = () => resolver(image);
        image.src = `/content/${inscription_id}`;
      })
  );

  let images = await Promise.all(promises);
  let canvas = new OffscreenCanvas(1024, 1024);

  let img = body.appendChild(document.createElement("img"));
  img.style.objectFit = "contain";
  img.style.width = img.style.height = "100%";

  await drawImage(images, canvas, img);
}

async function drawImage(images, canvas, img) {
  var newOpacity;
  if (state === null) {
    let now = new Date();
    let time =
      now.getHours() +
      (now.getMinutes() +
        (now.getSeconds() + now.getMilliseconds() / 1000) / 60) /
        60;
    newOpacity = Math.max(
      0,
      Math.min(
        1,
        (60 / 1.3) * (time - (7 + 2 / 15)),
        -(60 / 1.3) * (time - (19 + 0.155))
      )
    );
  } else {
    newOpacity = state;
  }

  if (newOpacity == opacity) return;
  opacity = newOpacity;

  let ctx = canvas.getContext("2d");
  for (let i of [...images.keys()]) {
    if (i == 1) ctx.globalAlpha = opacity;
    ctx.drawImage(images[i], 0, 0, canvas.width, canvas.height);
    ctx.globalAlpha = 1;
  }
  URL.revokeObjectURL(img.src);
  img.src = URL.createObjectURL(await canvas.convertToBlob());
}
