use tempfile::TempDir;
use std::fs;
use std::path::PathBuf;
use l_tool::commands::pdf::commands::{BundleArgs, PdfCommands, PaperKind, Orientation, SortKind, handle_pdf_command};

fn create_test_image_png(path: &PathBuf) {
    let img = image::RgbImage::from_fn(8, 8, |x, y| {
        image::Rgb([((x*30)%255) as u8, ((y*20)%255) as u8, 128])
    });
    img.save(path).expect("save png");
}

#[tokio::test]
async fn test_pdf_bundle_multiple_images_default_output() {
    let dir = TempDir::new().unwrap();
    let a = dir.path().join("a.png");
    let b = dir.path().join("b.png");
    create_test_image_png(&a);
    create_test_image_png(&b);

    let args = BundleArgs {
        inputs: vec![a.to_str().unwrap().to_string(), b.to_str().unwrap().to_string()],
        dir: None,
        output: PathBuf::from("l-tool-pdf-bundle.pdf"),
        paper: PaperKind::A4,
        orientation: Orientation::Portrait,
        sort: SortKind::Name,
        rotate: None,
    };

    // run in temp dir
    let original = std::env::current_dir().unwrap();
    std::env::set_current_dir(dir.path()).unwrap();
    handle_pdf_command(PdfCommands::Bundle(args)).await.unwrap();
    std::env::set_current_dir(original).unwrap();

    let output = dir.path().join("l-tool-pdf-bundle.pdf");
    assert!(output.exists());
    assert!(fs::metadata(output).unwrap().len() > 0);
}

#[tokio::test]
async fn test_pdf_bundle_dir_collect_and_custom_output() {
    let dir = TempDir::new().unwrap();
    let d = dir.path().join("imgs");
    fs::create_dir_all(&d).unwrap();
    let c = d.join("c.png");
    let dimg = d.join("d.png");
    create_test_image_png(&c);
    create_test_image_png(&dimg);

    let out = dir.path().join("bundle.pdf");
    let args = BundleArgs {
        inputs: vec![],
        dir: Some(d.clone()),
        output: out.clone(),
        paper: PaperKind::A4,
        orientation: Orientation::Landscape,
        sort: SortKind::Name,
        rotate: None,
    };

    handle_pdf_command(PdfCommands::Bundle(args)).await.unwrap();
    assert!(out.exists());
}
