use crate::layout::Page;
use printpdf::*;
use std::path::PathBuf;

pub fn generate_pdf(output_path: PathBuf, pages: Vec<Page>) {
    let mut doc = PdfDocument::new("Planches");

    let mut final_pages = Vec::new();

    for page in pages {
        let mut ops = Vec::new();

        for sticker in page.stickers {
            let image_bytes = std::fs::read(sticker.path).unwrap();
            let image = RawImage::decode_from_bytes(&image_bytes, &mut Vec::new()).unwrap();

            let image_id = doc.add_image(&image);

            ops.push(Op::UseXobject {
                id: image_id.clone(),
                transform: XObjectTransform {
                    translate_x: Some(Mm(sticker.position.x as f32).into()),
                    translate_y: Some(Mm(sticker.position.y as f32).into()),
                    rotate: Some(XObjectRotation {
                        angle_ccw_degrees: 0.0,
                        rotation_center_x: Px(0),
                        rotation_center_y: Px(0),
                    }),
                    scale_x: Some(1.0),
                    scale_y: Some(1.0),
                    dpi: Some(300.0),
                },
            });
        }

        let page = PdfPage::new(Mm(420.0), Mm(297.0), ops);

        final_pages.push(page)
    }

    let bytes = doc
        .with_pages(final_pages)
        .save(&PdfSaveOptions::default(), &mut Vec::new());

    std::fs::write(output_path, bytes).unwrap();
    println!("Created image_example.pdf");
}
