use gtk::{gio, prelude::*};

pub fn scan(screenshot: &gio::File) -> anyhow::Result<String> {
    let (data, _) = screenshot.load_contents(gio::Cancellable::NONE)?;

    scan_bytes(&data)
}

pub fn scan_bytes(data: &[u8]) -> anyhow::Result<String> {
    let img = image::load_from_memory(data)?.into_luma8();
    let mut prepared_img = rqrr::PreparedImage::prepare(img);
    let grids = prepared_img.detect_grids();
    let mut decoded = Vec::new();

    if let Some(grid) = grids.first() {
        grid.decode_to(&mut decoded)?;
    } else {
        anyhow::bail!("Invalid QR code")
    }

    Ok(String::from_utf8(decoded)?)
}
