nunc 0.2.0

WIP: time tracking application
Documentation
#![allow(clippy::zero_prefixed_literal)]

#[macro_use]
pub mod util;
pub mod cache;
pub mod config;
pub mod core;
pub mod cli;
pub mod data;
pub mod error;

#[cfg(test)]
pub mod tests;


use std::path::Path;

use rusqlite::Connection;

use error::{
	Error,
	Result
};
use config::Config;
use crate::core::Database;
use crate::cache::Cache;

pub struct Nunc {
	config: Config,
	db: Connection,
	cache: Cache
}

impl Nunc {
	#[cfg(test)]
	fn open_mem_db() -> rusqlite::Result<Connection> {
		let db = Connection::open_in_memory()?;
		db.pragma_update(None, "FOREIGN_KEYS", true)?;
		db.execute_batch(include_str!("../data/schema.sql"))?;
		Ok(db)
	}

	fn open_db(path: &Path) -> Result<Connection> {
		match path.exists() {
			true => {
				let db = Connection::open(path)?;
				db.pragma_update(None, "FOREIGN_KEYS", true)?;
				Ok(db)
			},
			false => Err(Error::not_found(&path.to_string_lossy()))
		}
	}

	pub fn load() -> Result<Self> {
		let path = Config::default_path();
		if !path.exists() {
			return Err(Error::NoConfig)
		}
		Self::load_with_config(&path)
	}
	pub fn load_with_config(path: &Path) -> Result<Self> {
		let config = Config::read(path)?;
		let db = Self::open_db(&config.db_path)?;
		let cache = config.open_cache()?;
		Ok(Self {config, db, cache})

	}

	pub fn config(&self) -> &Config {&self.config}

	pub(crate) fn from_connection(db: Connection) -> Result<Self> {
		let config = Config {
			db_path: "".into(),
			use_cache: None,
			cache_path: None
		};
		let cache = Cache::create_in_memory()?;
		Ok(Self {config, db, cache})
	}

	#[cfg(test)]
	pub fn testing() -> Result<Self> {
		let config = Config {
			db_path: "".into(),
			use_cache: None,
			cache_path: None
		};
		let db = Self::open_mem_db()?;
		let cache = Cache::create_in_memory()?;
		Ok(Self {config, db, cache})
	}
}

impl Database for Nunc {
	fn db(&self) -> &Connection {&self.db}
	fn cache(&self) -> &Cache {&self.cache}
}


#[test]
fn nunc_testing() {
	let _ = Nunc::testing().unwrap();
}