import domtoimage from "dom-to-image";

export class ScreenshotCtrl {
  async snap(options: { element: HTMLElement; ratio?: number }): Promise<Blob> {
    const dom = options.element;

    const transferEl = document.querySelector(".transfer") as
      | HTMLElement
      | undefined;
    if (transferEl) {
      transferEl.style.display = "none";
    }

    if (options.ratio) {
      const result = await domtoimage.toJpeg(dom);
      const img = await new Promise<HTMLImageElement>((resolve) => {
        const image = new Image();
        image.src = result;
        image.onload = function () {
          if (transferEl) {
            transferEl.style.display = "block";
          }
          resolve(image);
        };
      });
      const canvas = document.createElement("canvas");
      canvas.width = img.naturalWidth;
      canvas.height = Math.min(
        img.naturalWidth / options.ratio,
        img.naturalHeight
      );
      const ctx = canvas.getContext("2d");
      ctx?.drawImage(
        img,
        0,
        0,
        canvas.width,
        canvas.height,
        0,
        0,
        canvas.width,
        canvas.height
      );
      return new Promise((resolve) => {
        canvas.toBlob((blob) => {
          if (transferEl) {
            transferEl.style.display = "block";
          }
          if (blob) {
            resolve(blob);
          }
        });
      });
    } else {
      return domtoimage.toBlob(dom);
    }
  }
}
