use crate::formaters::format_time;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use std::{
fmt, fs,
io::{stdin, Write},
};
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Config {
pub rate: f32,
pub cost_per_shift: f32,
pub tax_percent: f32,
pub default_shift_length: f32,
pub currency: String,
}
impl Config {
pub fn new(config_path: String) -> Self {
println!("Creating config\n");
println!("{}", "What's your hourly rate?".yellow());
let rate = read_line().parse::<f32>().expect("Couldn't parse number");
println!(
"{}",
"What's your currency symbol (press enter for $)?".yellow()
);
let currency = read_line();
println!("{}", "What's your income tax percentage?".yellow());
let tax_percent = read_line().parse::<f32>().expect("Couldn't parse number") / 100.;
if tax_percent > 1. {
eprintln!("Tax percentage can't be bigger then a 100%");
}
println!(
"{}",
"How much should the default shift length be (use this format 8:00)?".yellow()
);
let default_shift_length =
crate::parse::parse_time(Some(read_line()), 0.).expect("Coulnd't parse time");
println!("{}", "How much do you pay per shift?".yellow());
let cost_per_shift = read_line().parse::<f32>().expect("Couldn't parse number");
let config = Config {
rate,
currency,
tax_percent,
cost_per_shift,
default_shift_length,
};
let config_file_path = format!("{}/config.json", &config_path);
if fs::metadata(&config_file_path).is_ok() {
println!(
"{}",
"Do you want to overwrite current config? Y/n".yellow()
);
let answer = read_line().to_lowercase();
if answer == "n" || answer == "no" {
fs::rename(
&config_file_path,
format!("{}/config.json.bak", &config_path),
)
.unwrap();
println!("{}", "Previous config saved as config.json.bak".green());
}
}
let mut config_file =
fs::File::create(config_file_path).expect("Error creating config file");
write!(config_file, "{}", serde_json::to_string(&config).unwrap()).unwrap();
println!("{}", "Successfully saved new config file".green());
config
}
}
impl fmt::Display for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Hourly rate: {}\nTax precentage: {}%\nCost per shift: {}\nCurrency symbol: {}\nDefault shift length: {}",
format!("{}{}", self.rate, self.currency).green(),
self.tax_percent.to_string().red(),
format!("{}{}", self.cost_per_shift, self.currency).red(),
self.currency,
format_time(self.default_shift_length).yellow()
)
}
}
fn read_line() -> String {
let mut input = String::from("");
stdin()
.read_line(&mut input)
.expect("Error getting the answer");
input.trim().to_string()
}