use fern::{
    colors::{Color, ColoredLevelConfig},
    Dispatch,
};
use log::debug;
use std::time::SystemTime;
pub fn setup_logger() {
    let colors_line = ColoredLevelConfig::new()
        .error(Color::Red)
        .warn(Color::Yellow)
        .info(Color::Green)
        .debug(Color::White)
        .trace(Color::BrightBlack);

    let colors_level = colors_line.info(Color::Green);
    let level = if cfg!(debug_assertions) {
        log::LevelFilter::Debug
    } else {
        log::LevelFilter::Info
    };

    let console_config = fern::Dispatch::new()
        .format(move |out, message, record| {
            out.finish(format_args!(
                "{colors_line}[{data} {level} {target} {colors_line}] {message}\x1B[0m",
                colors_line = format_args!(
                    "\x1B[{}m",
                    colors_line.get_color(&record.level()).to_fg_str()
                ),
                data = humantime::format_rfc3339_seconds(SystemTime::now()),
                target = record.target(),
                level = colors_level.color(record.level()),
                message = message,
            ));
        })
        .level(level)
        .chain(std::io::stdout());
    // .chain(fern::DateBased::new("program.log", "%Y-%m-%d"))
    // .apply()
    // .unwrap();
    let log_path = std::env::temp_dir().join("program.log");
    let file_config = fern::Dispatch::new()
        .format(move |out, message, record| {
            out.finish(format_args!(
                "[{data} {level} {target}] {message}",
                data = humantime::format_rfc3339_seconds(SystemTime::now()),
                target = record.target(),
                level = colors_level.color(record.level()),
                message = message,
            ));
        })
        .level(level)
        .chain(fern::DateBased::new(&log_path, "%Y-%m-%d"));

    Dispatch::new()
        .level(log::LevelFilter::Debug)
        .chain(console_config)
        .chain(file_config)
        .apply()
        .unwrap();

    debug!("logging initialized");
}
