use crate::lib::Book;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fs, io};
use tabled::{Table, Tabled};
extern crate xdg;
mod lib;
fn main() -> Result<(), io::Error> {
let xdg = xdg::BaseDirectories::with_prefix("rustary").unwrap();
let config = xdg.place_config_file("books.json")?;
let check = Path::new(&config).exists();
if !check {
let mut config_file = File::create(&config)?;
write!(&mut config_file, "[]")?;
}
let config: PathBuf = xdg
.find_config_file("books.json")
.expect("Book Database note found!");
let mut data = read_file(&config)?;
println!("(n) New Entry | (l) List Books | (q) Quit");
loop {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match input.trim() {
"n" => {
let book_new: Book = lib::Book::new();
data.push(book_new);
marshal_matters(&data, &config)?;
println!("(n) New Entry | (l) List Books | (q) Quit");
}
"l" => {
let table = Table::new(&data).to_string();
println!("{}", table);
println!("(n) New Entry | (l) List Books | (q) Quit");
}
"q" => break,
_ => {
println!("Wrong Input!");
println!("(n) New Entry | (l) List Books | (q) Quit");
continue;
}
}
}
Ok(())
}
fn marshal_matters(obj: &Vec<Book>, file: &PathBuf) -> Result<(), io::Error> {
fs::write(file, serde_json::to_string_pretty(&obj).unwrap())?;
Ok(())
}
fn read_file(file: &PathBuf) -> Result<Vec<Book>, io::Error> {
let get_data = {
let get_data = fs::read_to_string(file)?;
serde_json::from_str::<Vec<Book>>(&get_data).unwrap()
};
Ok(get_data)
}