let loadingSharp = false;
import { rgbaToThumbHash } from "thumbhash";

export async function generateThumbHash(image: { width: number, height: number }) {
  if (!loadingSharp) {
    loadingSharp = true;
    setTimeout(async () => {
      // @ts-ignore
      globalThis["sharp"] = (await import("sharp")).default;
    }, 1000);
    return;
  }

  // @ts-ignore
  const sharp = globalThis["sharp"] as typeof import("sharp");

  if (!sharp) return;

  const scaleFactor = 100 / Math.max(image.width, image.height);

  const smallWidth = Math.floor(image.width * scaleFactor);
  const smallHeight = Math.floor(image.height * scaleFactor);

  //@ts-ignore
  const smallImg = await sharp(image.fsPath)
    .resize(smallWidth, smallHeight)
    .withMetadata()
    .raw()
    .ensureAlpha()
    .toBuffer();

  const buffer = rgbaToThumbHash(smallWidth, smallHeight, smallImg);
  return Buffer.from(buffer).toString("base64");
}
