use std::fs;
use std::fs::read_to_string;
use std::io::Write;
use std::process::exit;
use serde_derive::Deserialize;
use crate::log::Type;
use crate::date::{year, month, day, hour, second, minute};
#[derive(Deserialize)]
pub struct Config{
pub application_version: String,
pub application_name: String,
pub formatting: String,
pub stdout: String,
pub filename: String
}
impl Config {
pub fn new()->Self{
let filename = "config.toml";
let contents = match read_to_string(filename) {
Ok(c) => c,
Err(_) =>{
let mut file= fs::File::create(filename).unwrap();
file.write(b"application_version = '*'
application_name = ''
formatting = 'y/m/d h:M:s l'
stdout = 'both'
filename = 'log'").unwrap();
"application_version = '*'
application_name = ''
formatting = 'y/m/d h:M:s l'
stdout = 'both'
filename = 'log'".to_string()
}
};
let data: Config = match toml::from_str(&contents) {
Ok(d) => d,
Err(_) => {
eprintln!("Unable to load data from `{}`", filename);
exit(1);
}
};
Self{application_name: data.application_name, application_version: data.application_version, formatting: data.formatting, stdout: data.stdout, filename: data.filename}
}
}
pub trait Formatting {
fn format(&self)->String;
fn is_type(&self) -> Type;
}
impl Formatting for String{
fn format(&self)-> String{
let format = Config::new().formatting;
let l = self.clone();
let formatted: String = format.chars().map(|x| match x {
'y' => year(),
'm' => month(),
'd' => day(),
'h' => hour(),
'M' => minute(),
's' => second(),
'l' => l.clone(),
_ => x.to_string(),
}).collect();
format!("{}\n",formatted)
}
fn is_type(&self) -> Type {
let format = Config::new().stdout.to_ascii_lowercase();
match format.as_str() {
"console" => Type::Terminal(self.clone()),
"log" => Type::Log(self.clone()),
"both" => Type::Bothe(self.clone()),
_ => Type::Log(self.clone())
}
}
}