var express = require('express');
var router = express.Router();
const utils = require('../../libs/utils');
const config = require('../../config/app');
const { PDFDocument, rgb, StandardFonts } = require('pdf-lib');


router.get('/pdf/:id', function (req, res, next) {
  (async function () {
    let id = req.params.id;
    utils.validators.validateId(id);

    let host = config.cdnHost ?? config.resHost;

    let url = `${host}/thumbs/coloring-page/page/1200/${id}.jpeg`;

    try {
      const response = await fetch(url);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const arrayBuffer = await response.arrayBuffer();

      const padding = 40;
      const pdfDoc = await PDFDocument.create();
      const page = pdfDoc.addPage();

      const image = await pdfDoc.embedJpg(arrayBuffer); // pdf-lib支持jpg，png

      // 获取图片原始尺寸
      const imageWidth = image.width;
      const imageHeight = image.height;

      // 计算带 padding 的图片绘制区域
      const pageWidth = page.getWidth();
      const pageHeight = page.getHeight();

      // 计算缩放比例，保证图片在带 padding 的区域内
      let scaledWidth = imageWidth;
      let scaledHeight = imageHeight;

      if (imageWidth + 2 * padding > pageWidth || imageHeight + 2 * padding > pageHeight) {
        const widthScale = (pageWidth - 2 * padding) / imageWidth;
        const heightScale = (pageHeight - 2 * padding) / imageHeight;
        const scale = Math.min(widthScale, heightScale);
        scaledWidth = imageWidth * scale;
        scaledHeight = imageHeight * scale;
      }

      // 计算图片绘制的起始坐标
      const x = (pageWidth - scaledWidth) / 2;
      const y = (pageHeight - scaledHeight) / 2;

      // 绘制图片，并留出 padding
      page.drawImage(image, {
        x: x,
        y: y,
        width: scaledWidth,
        height: scaledHeight,
      });


      const pdfBytes = await pdfDoc.save();

      res.setHeader('Content-Type', 'application/pdf');
      res.setHeader('Content-Disposition', `attachment; filename=${id}.pdf`);
      res.send(Buffer.from(pdfBytes));

    } catch (error) {
      console.error(`Error fetching image: ${id}`, error);
    }


  })().catch(next)
});



module.exports = router;
