use database::Database;
use endpoint::execute::ExecuteError;
use extension::folder::Folder;

use std::io;

pub fn execute_foldl<R>(journal_name: &[u8], using: &[u8], extension: &[u8],
                        database: &Database, respond: R)
                        -> Result<(), ExecuteError>
    where R: for<'a> FnOnce(&'a [u8]) -> io::Result<()> {
    let extension = database.get_extension(extension)?;
    let mut folder = Folder::initialize(&extension, using)?;

    let concurrent_journal = database.get_journal(journal_name)?;
    let mut journal = concurrent_journal.read()?;

    for entry in journal.iter()? {
        folder.step(&entry?)?;
    }

    let accumulator = folder.finalize()?;
    respond(&accumulator)?;
    Ok(())
}
