// Rshare - a file sharing program written in Rust.
// Copyright (C) 2017 Cooper Paul EdenDay
//
// This program 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.
//
// This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
//
// Electronic mail: cedenday@protonmail.com
// Paper mail: 100 Front Street, #31, Bath, Maine, 04530, USA

use log;
use app_dirs;
use APP_DATA;

pub struct Logger;

impl log::Log for Logger {
    fn enabled(&self, metadata: &log::LogMetadata) -> bool {
        metadata.level() <= log::LogLevel::Info
    }

    fn log(&self, record: &log::LogRecord) {
        if self.enabled(record.metadata()) {
            use std;
            use std::io::Write;

            let path = app_dirs::app_dir(app_dirs::AppDataType::UserData, &APP_DATA, "");
            if let Ok(mut path) = path {
                path.push("log.txt");

                let seconds_past_epoch = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs();
                let buffer = format!("[{}] {}: {}\n",
                                     seconds_past_epoch,
                                     record.level(),
                                     record.args());

                let file = std::fs::OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(&path);
                if let Ok(file) = file {
                    let mut writer = std::io::BufWriter::new(file);
                    writer.write_all(buffer.as_bytes()).unwrap();
                    writer.flush().unwrap();
                } else {
                    println!("Couldn't write '{}' to log file.", buffer);
                }
            } else {
                println!("Couldn't open logging directory.");
            }
        }
    }
}

pub fn init() -> Result<(), log::SetLoggerError> {
    log::set_logger(|max_log_level| {
                        max_log_level.set(log::LogLevelFilter::Info);
                        Box::new(Logger)
                    })
}
