use crate::runtime::Runtime;
use crate::support::pdf;
use crate::types::FileInfo;
use crate::{Error, Result};
use mlua::{IntoLua, Lua, Table, Value};
use simple_fs::SPath;
pub fn init_module(lua: &Lua, runtime: &Runtime) -> Result<Table> {
let table = lua.create_table()?;
let page_count_fn = lua.create_function(move |_lua, path: String| page_count(path))?;
let rt = runtime.clone();
let page_split_fn = lua
.create_function(move |lua, (path, dest_dir): (String, Option<String>)| page_split(lua, &rt, path, dest_dir))?;
table.set("page_count", page_count_fn)?;
table.set("split_pages", page_split_fn)?;
Ok(table)
}
fn page_count(path: String) -> mlua::Result<usize> {
let spath =
SPath::from_std_path(&path).map_err(|err| Error::custom(format!("aip.pdf.page_count failed. {err}")))?;
let doc = pdf::load_pdf_doc(&spath).map_err(|err| Error::custom(format!("aip.pdf.page_count failed. {err}")))?;
Ok(pdf::page_count(&doc))
}
fn page_split(lua: &Lua, runtime: &Runtime, path: String, dest_dir: Option<String>) -> mlua::Result<Value> {
let pdf_path =
SPath::from_std_path(&path).map_err(|err| Error::custom(format!("aip.pdf.page_split failed. {err}")))?;
if !pdf_path.exists() {
return Err(Error::custom(format!("aip.pdf.page_split failed. File not found: {path}")).into());
}
let dest_dir_path = if let Some(dir) = dest_dir {
SPath::new(dir)
} else {
let parent = pdf_path.parent().unwrap_or_else(|| SPath::new("."));
let stem = pdf_path.stem();
parent.join(stem)
};
let created_files = pdf::split_pdf_pages(&pdf_path, &dest_dir_path)
.map_err(|err| Error::custom(format!("aip.pdf.page_split failed. {err}")))?;
let file_infos: Vec<FileInfo> = created_files
.into_iter()
.map(|full_path| FileInfo::new(runtime.dir_context(), full_path.clone(), &full_path))
.collect();
file_infos.into_lua(lua)
}