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

let s: typeof import("sharp") | undefined;

async function getSharp(): Promise<typeof import("sharp") | undefined> {

  if (s) return s;

  if (import.meta.env.MODE !== "development") {
    s = (await import("sharp")).default;
    return s;
  }

  if (!loadingSharp) {
    loadingSharp = true;
    setTimeout(async () => {
      s = (await import("sharp")).default;
    }, 1000);
    return;
  }
}

export async function generateThumbHash(image: { width: number, height: number }) {

  const sharp = await getSharp();
  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");
}
