use std::str;
use std::path::Path;
use std::io::{self, Write};
use std::fs::{self, OpenOptions, File};
use strip_ansi_escapes::strip;

pub struct FileWriter {
    file_handle: File,
}

impl FileWriter {
    pub fn new<T: AsRef<str> + ToString>(
        file_path: T,
    ) -> Box<dyn Write> {
        let file_path = file_path.to_string();

        let path = Path::new(&file_path);
        let prefix = path.parent()
            .expect(
                &format!("Cannot get parent folder of [{}]", &file_path)
            );

        let parent_path_string = prefix.to_str().expect(
            &format!("Cannot convert parent path [{:?}] to string.", prefix)
        );

        fs::create_dir_all(&parent_path_string)
            .expect(
                &format!("Cannot create folder at [{}]", &parent_path_string)
            );

        let file_handle = OpenOptions::new()
            .create(true)
            .write(true)
            .append(true)
            .open(&file_path)
            .expect(
                &format!("Cannot open file at [{}].", &file_path),
            );

        return Box::new(FileWriter { file_handle });
    }
}

impl Write for FileWriter
 {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let no_ansi_color_buf = strip(buf)
            .expect("Failed to stip the ANSI escape sequences.");

        // write the contents
        self.file_handle.write(&no_ansi_color_buf)
            .expect("Cannot write to the file.");

        return Ok(no_ansi_color_buf.len());
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file_handle.flush()
            .expect("Failed to flush into the file.");

        return Ok(());
    }
}
