use crate::config::Config;
use crate::stickers::*;

#[derive(Debug)]
pub struct Page {
    pub stickers: Vec<Sticker>,
}

pub fn generate_page(sticker_details: Vec<StickerDetail>) -> Vec<Page> {
    let config = Config::load_a4();
    let mut pages: Vec<Page> = vec![];

    let mut current_page = Page {
        stickers: vec![]
    };

    for sticker_detail in sticker_details {
        if !sticker_detail.path.is_file() {
            panic!("Erreur d'ouverture du fichier : {:?}", sticker_detail.path)
        }

        let total_width = total_width(&config, sticker_detail.width);
        let total_height = total_height(&config, sticker_detail.height);

        let rows = (usable_width(&config) / total_width).floor() as usize;
        let cols = (usable_height(&config) / total_height ).floor() as usize;

        let stickers_per_page = rows * cols;

        let mut remaining = sticker_detail.number;

        while remaining > 0 {
            let index = current_page.stickers.len();

            let i = index / cols;
            let j = index % cols;

            let position_x = config.bleed_mm + (j as f64) * total_width;
            let position_y = config.bleed_mm + (i as f64) * total_height;

            current_page.stickers.push(create_sticker(sticker_detail.clone(), position_x, position_y));
            remaining -= 1;

            let index = current_page.stickers.len();

            if index == stickers_per_page {
                pages.push(current_page);
                current_page = Page { stickers: vec![] };
            }

        }
    }

    if !current_page.stickers.is_empty() {
        pages.push(current_page);
    }

    pages
}

fn create_sticker(sticker_detail: StickerDetail, x: f64, y: f64) -> Sticker {
    Sticker {
        path: sticker_detail.path,
        position: Position { x, y },
        width: sticker_detail.width,
        height: sticker_detail.width
    }
}

fn usable_width(config: &Config) -> f64 {
    config.page_width_mm - 2.0 * config.bleed_mm
}

fn usable_height(config: &Config) -> f64 {
    config.page_height_mm - 2.0 * config.bleed_mm
}

fn total_width(config: &Config, width: f64) -> f64 {
    width + config.spacing_mm
}

fn total_height(config: &Config, height: f64) -> f64 {
    height + config.spacing_mm
}
