use crate::error::Result;
use crate::model::CompressionLevel;
use flate2::{write::ZlibEncoder, Compression};
use std::io::Write;

pub fn flate_compress(data: &[u8], level: CompressionLevel) -> Result<Vec<u8>> {
    let compression = match level {
        CompressionLevel::None => {
            return Ok(data.to_vec());
        }
        CompressionLevel::Fast => Compression::fast(),
        CompressionLevel::Default => Compression::default(),
        CompressionLevel::Best => Compression::best(),
    };
    let mut encoder = ZlibEncoder::new(Vec::new(), compression);
    encoder.write_all(data)?;
    Ok(encoder.finish()?)
}

pub fn flate_stream_dictionary(data: &[u8], level: CompressionLevel) -> Result<(Vec<u8>, Vec<u8>)> {
    let compressed = flate_compress(data, level)?;
    let dictionary = format!("<< /Length {} /Filter /FlateDecode >>", compressed.len()).into_bytes();
    Ok((dictionary, compressed))
}
