// use std::fs::OpenOptions;
// use std::process::Command;
use chrono::Local;
use env_logger::Builder;
use log::LevelFilter;
use std::io::Write;
// use tokio::fs::File;
// use tokio::io::BufWriter;
use crate::utils::get_container_id;

// struct CustomLogger<W: Write> {
//     stdout: W,
//     file_writer: BufWriter<File>,
// }

/// # Fn `setup_logger`
/// ## for initializing process of unstoppable grubbing metrics.
/// 
/// *input*      : `Result<()>`
///
/// *output*     : `Err` if it cant create logger | `Ok` after logger initialing
///
/// *initiator*  : main thread
///
/// *managing*   : -
///
/// *depends on* : -  
/// 
pub fn setup_logger() -> Result<(), crate::options::structs::CustomError> {
    // if Command::new("sh").args(["-c", "mkdir logs"]).output().is_err() {
    //     println!("Error: Cannot init logs directory");
    //     std::process::exit(1);
    // }
    //
    // let log_target = Box::new(OpenOptions::new().create(true).append(true).open("./logs/runner.log").unwrap_or_else(|_| {
    //     println!("Error: Cannot create local log-file in /logs/runner.log, returning...");
    //     std::process::exit(1);
    // }));

    // building logger with current output format
    Builder::new()
        .format(move |buf, record| {
            writeln!(
                buf,
                "|{}| {} [{}] - {}",
                get_container_id().unwrap_or("NODE".to_string()).trim(),
                Local::now().format("%d-%m-%Y %H:%M:%S"),
                record.level(),
                record.args(),
            )
        })
        .filter(None, LevelFilter::Info)
        .target(env_logger::Target::Stdout)
        // temporary deprecated
        // .target(env_logger::Target::Pipe(log_target))
        .init();

    Ok(())
}

#[cfg(test)]
mod logger_tests {
    use super::*;
    // #[test]
    // fn setting_up_logger() {
    //     assert!(setup_logger().is_ok());
    // }

    #[test]
    fn setting_up_logger() {
        Builder::new()
            .format(move |buf, record| {
                writeln!(
                    buf,
                    "|{}| {} [{}] - {}",
                    get_container_id().unwrap_or("NODE".to_string()).trim(),
                    Local::now().format("%d-%m-%Y %H:%M:%S"),
                    record.level(),
                    record.args(),
                )
            })
            .filter(None, LevelFilter::Info)
            .target(env_logger::Target::Stdout)
            .is_test(true)
            .init();
    }
}
