import qrcode from "qrcode";

export const generateQRCode = async (link: string) => {
  try {
    const qrCodeDataURL = await qrcode.toDataURL(link);
    return qrCodeDataURL;
  } catch (error) {
    console.error("Error generating QR code:", error);
    return null;
  }
};

// Radial Progress PNGs were generated with only two colors
// and they use some baseline score (10%, 20%, 30%..)
type RADIAL_PROGRESS_COLOR = "laranja" | "azul";

export const getRadialProgressPNG = (
  color: RADIAL_PROGRESS_COLOR,
  score: number,
  total: number
) => {
  // calculate the percentage of the score
  // and round it to the closest available image
  const percent = (score / total) * 100;
  if (isNaN(percent)) return `public/radial_progress/${color}_0.png`;
  const remainder = percent % 10;
  const roundedPercent = percent - remainder;
  return `public/radial_progress/${color}_${roundedPercent}.png`;
};

export const streamToBuffer = async (
  stream: NodeJS.ReadableStream
): Promise<Buffer> => {
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    stream.on("data", (data) => {
      chunks.push(data);
    });
    stream.on("end", () => {
      resolve(Buffer.concat(chunks));
    });
    stream.on("error", reject);
  });
};
