//! C FFI for cpdf compression operations.

use super::document::CPDF_DOCS;
use super::{clear_error, set_error};
use crate::cpdf::compression;
use crate::ffi::Handle;

#[unsafe(no_mangle)]
pub extern "C" fn cpdf_compress(doc: Handle) -> Handle {
    clear_error();
    let d = match CPDF_DOCS.get(doc) {
        Some(arc) => arc.lock().unwrap().clone(),
        None => {
            set_error(1, &format!("invalid handle: {doc}"));
            return 0;
        }
    };
    match compression::compress_streams(d) {
        Ok(doc) => CPDF_DOCS.insert(doc),
        Err(e) => {
            set_error(1, &e.to_string());
            0
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn cpdf_decompress(doc: Handle) -> Handle {
    clear_error();
    let d = match CPDF_DOCS.get(doc) {
        Some(arc) => arc.lock().unwrap().clone(),
        None => {
            set_error(1, &format!("invalid handle: {doc}"));
            return 0;
        }
    };
    match compression::decompress_streams(d) {
        Ok(doc) => CPDF_DOCS.insert(doc),
        Err(e) => {
            set_error(1, &e.to_string());
            0
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn cpdf_squeeze(doc: Handle) -> Handle {
    clear_error();
    let d = match CPDF_DOCS.get(doc) {
        Some(arc) => arc.lock().unwrap().clone(),
        None => {
            set_error(1, &format!("invalid handle: {doc}"));
            return 0;
        }
    };
    match compression::squeeze(d) {
        Ok(doc) => CPDF_DOCS.insert(doc),
        Err(e) => {
            set_error(1, &e.to_string());
            0
        }
    }
}
