#[cfg(feature = "lz4")]
use anyhow::Result;
#[cfg(feature = "lz4")]
use log::*;
#[cfg(feature = "lz4")]
use std::io::Write;

#[cfg(feature = "lz4")]
use lz4_flex::frame::{FrameDecoder, FrameEncoder};
#[cfg(feature = "lz4")]
use std::fs::File;
#[cfg(feature = "lz4")]
use std::io::Read;
#[cfg(feature = "lz4")]
use std::path::PathBuf;

#[cfg(feature = "lz4")]
use crate::compression_engine::CompressionEngine;

#[cfg(feature = "lz4")]
#[derive(Debug, Eq, PartialEq, Clone, Default)]
pub struct CompressionEngineLZ4 {}

#[cfg(feature = "lz4")]
impl CompressionEngineLZ4 {
    pub fn new() -> CompressionEngineLZ4 {
        CompressionEngineLZ4 {}
    }
}

#[cfg(feature = "lz4")]
impl CompressionEngine for CompressionEngineLZ4 {
    fn open(&self, file_path: PathBuf) -> Result<Box<dyn Read + Send>> {
        debug!("COMPRESSION: Opening {:?} using {:?}", file_path, *self);

        let file = File::open(file_path)?;
        Ok(Box::new(FrameDecoder::new(file)))
    }

    fn create(&self, file_path: PathBuf) -> Result<Box<dyn Write>> {
        debug!("COMPRESSION: Writing to {:?} using {:?}", file_path, *self);

        let file = File::create(file_path)?;
        let lz4_write = FrameEncoder::new(file).auto_finish();

        Ok(Box::new(lz4_write))
    }

    fn clone_box(&self) -> Box<dyn CompressionEngine> {
        Box::new(self.clone())
    }
}
