use app_dirs::{self, AppDataType, AppInfo};
use std::{
fs::{create_dir_all, read_to_string, File},
io::{BufWriter, Write},
path::{Path, PathBuf},
};
const APP_INFO: AppInfo = AppInfo {
name: "evry",
author: "seanbreckenridge",
};
#[derive(Debug, Default)]
pub struct LocalDir {
pub root_dir: PathBuf,
}
impl LocalDir {
pub fn new() -> Self {
let dir_info: PathBuf = app_dirs::get_app_root(AppDataType::UserData, &APP_INFO)
.expect("Couldn't get users local data directory");
create_dir_all(dir_info.as_path()).expect("Could not create evry local directory");
create_dir_all(dir_info.as_path().join(Path::new("data")))
.expect("Could not create data directory");
Self { root_dir: dir_info }
}
}
pub fn read_epoch_millis(filepath: &str) -> u128 {
let millis_str = read_to_string(filepath).expect("Could not read tag information from file");
millis_str
.parse()
.expect("Could not convert tag file information to integer")
}
#[derive(Debug)]
pub struct Tag {
pub name: String,
pub path: String,
}
impl Tag {
pub fn new(name: String, local_dir: &LocalDir) -> Self {
let mut buf = local_dir.root_dir.clone();
buf.push("data");
buf.push(&name);
let path = buf.into_os_string().into_string().unwrap();
Self { name, path }
}
pub fn file_exists(&self) -> bool {
Path::new(&self.path).exists()
}
pub fn read_epoch_millis(&self) -> u128 {
read_epoch_millis(&self.path)
}
pub fn write(&self, time: u128) {
let fp = File::create(&self.path).expect("Could not create tag file");
let mut writer = BufWriter::new(&fp);
write!(&mut writer, "{}", time).expect("Could not write to file")
}
}