use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use crate::learned::Learned;
mod path {
extern crate directories;
use chrono::prelude::*;
use directories::UserDirs;
use std::fs::DirBuilder;
use std::path::{Path, PathBuf};
extern crate chrono;
pub fn get_file_name_from_path(file_path: &Path) -> &str {
let path: &str = file_path.to_str().unwrap();
let path_bits: Vec<&str> = path.rsplit("/").collect();
return path_bits[0];
}
pub fn get_til_path() -> PathBuf {
let user_dirs = UserDirs::new().expect("Could not find valid $HOME path");
let docs_dir = user_dirs.document_dir().expect("Could not locate user documents directory");
let mut til_dir: PathBuf = docs_dir.to_path_buf();
til_dir.push(".til");
if false == til_dir.exists() {
DirBuilder::new().create(&til_dir).expect("Could not create til directory in user documents");
}
til_dir
}
pub fn get_til_file_path(root_path: &Path, file_date: Date<Local>) -> PathBuf {
let mut file_path = root_path.to_path_buf();
file_path.push(file_date.format("%Y-%m-%d.md").to_string());
file_path
}
}
fn append_to_file(file_path: &Path, to_write: &str, prefix: &str) {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(file_path)
.expect("Could not open file for appending.");
writeln!(file, "{}", [prefix, to_write].join(" "))
.expect("Could not append to file");
}
pub fn write_til_file(learned: &Learned) {
let til_path = path::get_til_path();
let til_path = til_path.as_path();
let file_to_learn_into = path::get_til_file_path(til_path, learned.date);
if !file_to_learn_into.exists() {
append_to_file(&file_to_learn_into, &path::get_file_name_from_path(&file_to_learn_into).replace(".md", ""), "#");
}
append_to_file(&file_to_learn_into, learned.description.as_str(), "*");
}