use std::io::stdout;

use log::LevelFilter;
use yggdrasil_rt::debug::TraceLevel;

struct LogSink;

impl log::Log for LogSink {
    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &log::Record) {
        // debug_trace!("[{}] {}", record.level(), record.args());
        let trace_level = match record.level() {
            log::Level::Trace | log::Level::Debug => TraceLevel::Debug,
            log::Level::Info => TraceLevel::Info,
            log::Level::Warn => TraceLevel::Warn,
            log::Level::Error => TraceLevel::Error,
        };
        let message = format!("{}", record.args());
        unsafe { yggdrasil_rt::sys::debug_trace(trace_level, &message) };

        if unsafe { TO_STDOUT } {
            use std::io::Write;
            let mut stdout = stdout();
            writeln!(stdout, "[{}] {}", record.level(), record.args()).ok();
        }
    }

    fn flush(&self) {

    }
}

static SINK: LogSink = LogSink;
static mut TO_STDOUT: bool = true;

pub fn setup_logging(stdout: bool) {
    unsafe { TO_STDOUT = stdout };
    log::set_max_level(LevelFilter::Debug);
    log::set_logger(&SINK).unwrap();
}
