use chrono::Local;
use colored::{Color, Colorize};
use env_logger::fmt::Formatter;
use fern::Dispatch;
use log::Level;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::{env, fs, thread};

/// 获取可执行文件所在目录
pub fn get_current_dir() -> PathBuf {
    PathBuf::from(
        env::current_exe()
            .expect("获取可执行文件路径失败！")
            .parent()
            .expect("获取可执行文件所在目录失败！"),
    )
}
pub fn get_log_path() -> PathBuf {
    let exe_path = get_current_dir().join("log");
    if !exe_path.exists() {
        fs::create_dir_all(&exe_path).expect("创建日志目录失败！");
    }
    exe_path
}
fn get_time() -> String {
    let now = Local::now();
    now.format("%Y-%m-%d %H:%M:%S").to_string()
}

pub fn init_log(is_debug: bool) {
    let mut console_dispatch = Dispatch::new()
        .format(|out, message, record| {
            let (color, title) = match record.level() {
                Level::Error => (Color::Red, "Error"),
                Level::Warn => (Color::Yellow, "Warning"),
                Level::Info => (Color::Green, "Info"),
                Level::Debug => (Color::BrightWhite, "Debug"),
                Level::Trace => (Color::White, "Trace"),
            };

            out.finish(format_args!(
                "[{} {}]\t{}",
                get_time(),
                title.color(color),
                message
            ))
        })
        //.chain(fern::log_file(get_log_path().join("app.log")).expect("无法写入日志文件"))
        .chain(std::io::stdout());

    if is_debug {
        console_dispatch = console_dispatch.level(log::LevelFilter::Debug);
    } else {
        console_dispatch = console_dispatch.level(log::LevelFilter::Info);
    }
    console_dispatch.apply().expect("写入日志失败");
}
