use env_logger::{Builder, Env};
use log::{error, info, warn};
use std::fs::OpenOptions;
use std::io::Write;

/// 日志记录工具类
///
/// 示例
/// ```rust
/// use mitoo::LogUtil;
/// 
/// fn it_works() {
///     let log_util = LogUtil;
///     log_util.init("app.log");
///     log_util.info("This is an info log");
///     log_util.warn("This is a warning log");
///     log_util.error("This is an error log");
/// }
/// ```
pub struct LogUtil;

impl LogUtil {
    /// 初始化日志记录器，将日志记录到文件
    pub fn init(&self, log_file_path: &str) {
        let file = OpenOptions::new()
            .write(true)
            .append(true)
            .create(true)
            .open(log_file_path).expect("Failed to create log file");
        let env = Env::default().filter_or("RUST_LOG", "info");
        Builder::from_env(env)
            .format(|buf, record| {
                writeln!(
                    buf,
                    "[{}][{}] {}",
                    chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"),
                    record.level(),
                    record.args()
                )
            })
            .target(env_logger::Target::Pipe(
                Box::new(file) as Box<dyn std::io::Write + Send + 'static>
            ))
            .init();
    }

    /// 记录信息级别日志消息
    ///
    /// 该函数用于输出信息级别的日志，通常用于记录程序运行过程中的重要信息。
    pub fn info(&self, message: &str) {
        info!("{}", message);
    }

    /// 记录信息级别日志消息
    ///
    /// 该函数用于输出错误级别的日志。
    pub fn error(&self, message: &str) {
        error!("{}", message);
    }

    /// 记录信息级别日志消息
    ///
    /// 该函数用于输出告警级别的日志。
    pub fn warn(&self, message: &str) {
        warn!("{}", message);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn it_works() {
        let log_util = LogUtil;
        log_util.init("app.log");
        log_util.info("This is an info log");
        log_util.warn("This is a warning log");
        log_util.error("This is an error log");
    }
}
