/*
 * melib
 *
 * Copyright 2019 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

use std::path::PathBuf;
use std::sync::{Arc, Mutex};

#[derive(Copy, Clone, PartialEq, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum LoggingLevel {
    OFF,
    FATAL,
    ERROR,
    WARN,
    INFO,
    DEBUG,
    TRACE,
}

impl std::fmt::Display for LoggingLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                OFF => "OFF",
                FATAL => "FATAL",
                ERROR => "ERROR",
                WARN => "WARN",
                INFO => "INFO",
                DEBUG => "DEBUG",
                TRACE => "TRACE",
            }
        )
    }
}

mod helpers {
    #[allow(unused_variables)]
    extern crate wasm_bindgen;

    use wasm_bindgen::prelude::*;
    #[wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = console)]
        pub fn log(s: &str);
    }

    pub(super) use log as js_console;
}
use helpers::js_console;

impl Default for LoggingLevel {
    fn default() -> Self {
        LoggingLevel::INFO
    }
}

use LoggingLevel::*;

struct LoggingBackend {
    level: LoggingLevel,
}

thread_local!(static LOG: Arc<Mutex<LoggingBackend>> = Arc::new(Mutex::new({
    //let data_dir = xdg::BaseDirectories::with_prefix("meli").unwrap();
    LoggingBackend {
        level: LoggingLevel::default(),
    }}))
);

pub fn log<S: AsRef<str>>(val: S, level: LoggingLevel) {
    LOG.with(|f| {
        let b = f.lock().unwrap();
        let val = val.as_ref();
        if level <= b.level {
            js_console(&format!(
                "{} [{}]: {}\n",
                crate::datetime::timestamp_to_string(crate::datetime::now(), None),
                level.to_string(),
                val
            ));
        }
    });
}

pub fn get_log_level() -> LoggingLevel {
    let mut level = INFO;
    LOG.with(|f| {
        level = f.lock().unwrap().level;
    });
    level
}

pub fn change_log_dest(path: PathBuf) {
    LOG.with(|f| {});
}

pub fn change_log_level(new_val: LoggingLevel) {
    LOG.with(|f| {
        let mut backend = f.lock().unwrap();
        backend.level = new_val;
    });
}
