mod bookmark;
mod database;
mod identity;
use bookmark::Bookmark;
use database::Database;
use identity::Identity;
use gtk::glib::{user_config_dir, DateTime};
use sqlite::{Connection, Transaction};
use std::{fs::create_dir_all, path::PathBuf, rc::Rc, sync::RwLock};
const VENDOR: &str = "YGGverse";
const APP_ID: &str = "Yoda";
const BRANCH: &str = "master";
const DB_NAME: &str = "database.sqlite3";
pub struct Profile {
pub bookmark: Rc<Bookmark>,
pub database: Rc<Database>,
pub identity: Rc<Identity>,
pub config_path: PathBuf,
}
impl Profile {
pub fn new() -> Self {
let mut config_path = user_config_dir();
config_path.push(VENDOR);
config_path.push(APP_ID);
config_path.push(BRANCH);
config_path.push(format!(
"{}.{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR")
));
if let Err(reason) = create_dir_all(&config_path) {
panic!("{reason}")
}
let mut database_path = config_path.clone();
database_path.push(DB_NAME);
let connection = match Connection::open(database_path.as_path()) {
Ok(connection) => Rc::new(RwLock::new(connection)),
Err(reason) => panic!("{reason}"),
};
{
let mut connection = match connection.write() {
Ok(connection) => connection,
Err(reason) => todo!("{reason}"),
};
let transaction = match connection.transaction() {
Ok(transaction) => transaction,
Err(reason) => todo!("{reason}"),
};
match migrate(&transaction) {
Ok(_) => {
if let Err(reason) = transaction.commit() {
todo!("{reason}")
}
}
Err(reason) => todo!("{reason}"),
}
}
let database = Rc::new(Database::new(connection.clone()));
let profile_id = Rc::new(match database.active().unwrap() {
Some(profile) => profile.id,
None => match database.add(true, DateTime::now_local().unwrap(), None) {
Ok(id) => id,
Err(reason) => todo!("{:?}", reason),
},
});
let bookmark = Rc::new(Bookmark::new(connection.clone(), profile_id.clone()));
let identity = Rc::new(match Identity::new(connection, profile_id) {
Ok(result) => result,
Err(reason) => todo!("{:?}", reason.to_string()),
});
Self {
bookmark,
identity,
database,
config_path,
}
}
}
pub fn migrate(tx: &Transaction) -> Result<(), String> {
if let Err(reason) = database::init(tx) {
return Err(reason.to_string());
}
bookmark::migrate(tx)?;
identity::migrate(tx)?;
Ok(())
}