use crate::error::{Error, Result};
use once_cell::sync::OnceCell;
use serde_json::Value;
use std::sync::{Arc, RwLock};
static APP_REPOSITORY: OnceCell<Arc<RwLock<Value>>> = OnceCell::new();
static MAIN_REPOSITORY: OnceCell<Arc<RwLock<Value>>> = OnceCell::new();
pub struct APP;
pub struct MAIN;
impl APP {
pub fn init(data: Value) -> Result<()> {
let repository = Arc::new(RwLock::new(data));
APP_REPOSITORY.set(repository.clone()).map_err(|_| {
Error::internal("APP repository has already been initialized".to_string())
})?;
MAIN_REPOSITORY.set(repository).map_err(|_| {
Error::internal("MAIN repository has already been initialized".to_string())
})?;
Ok(())
}
pub fn get_repository() -> Option<Arc<RwLock<Value>>> {
APP_REPOSITORY.get().cloned()
}
pub fn get<T: serde::de::DeserializeOwned>(path: &str) -> Option<T> {
let repo = APP_REPOSITORY.get()?;
let value = repo.read().ok()?;
let result = Self::get_nested(&value, path)?;
serde_json::from_value(result.clone()).ok()
}
pub fn get_string(path: &str) -> Option<String> {
Self::get(path)
}
pub fn get_int(path: &str) -> Option<i64> {
let repo = APP_REPOSITORY.get()?;
let value = repo.read().ok()?;
let result = Self::get_nested(&value, path)?;
match result {
Value::Number(n) => n.as_i64().or_else(|| n.as_u64().map(|u| u as i64)),
_ => None,
}
}
pub fn get_bool(path: &str) -> Option<bool> {
Self::get(path)
}
pub fn get_or<T: serde::de::DeserializeOwned>(path: &str, default: T) -> T {
Self::get(path).unwrap_or(default)
}
pub fn set<T: serde::Serialize>(path: &str, value: T) -> Result<()> {
let repo = APP_REPOSITORY
.get()
.ok_or_else(|| Error::internal("APP repository not initialized".to_string()))?;
let json_value = serde_json::to_value(value)?;
let mut data = repo
.write()
.map_err(|e| Error::internal(format!("Failed to lock APP repository: {}", e)))?;
Self::set_nested(&mut data, path, json_value);
Ok(())
}
pub fn remove(path: &str) -> Result<()> {
let repo = APP_REPOSITORY
.get()
.ok_or_else(|| Error::internal("APP repository not initialized".to_string()))?;
let mut data = repo
.write()
.map_err(|e| Error::internal(format!("Failed to lock APP repository: {}", e)))?;
Self::remove_nested(&mut data, path);
Ok(())
}
pub fn has(path: &str) -> bool {
if let Some(repo) = APP_REPOSITORY.get() {
if let Ok(data) = repo.read() {
return Self::get_nested(&data, path).is_some();
}
}
false
}
pub fn clear() -> Result<()> {
let repo = APP_REPOSITORY
.get()
.ok_or_else(|| Error::internal("APP repository not initialized".to_string()))?;
let mut data = repo
.write()
.map_err(|e| Error::internal(format!("Failed to lock APP repository: {}", e)))?;
*data = Value::Object(serde_json::Map::new());
Ok(())
}
pub fn is_initialized() -> bool {
APP_REPOSITORY.get().is_some()
}
fn get_nested<'a>(obj: &'a Value, path: &str) -> Option<&'a Value> {
let parts: Vec<&str> = path.split('.').collect();
let mut current = obj;
for part in parts {
match current {
Value::Object(map) => {
current = map.get(part)?;
}
_ => return None,
}
}
Some(current)
}
fn set_nested(obj: &mut Value, path: &str, value: Value) {
let parts: Vec<&str> = path.split('.').collect();
if parts.is_empty() {
return;
}
if parts.len() == 1 {
if let Value::Object(map) = obj {
map.insert(parts[0].to_string(), value);
}
return;
}
if !obj.is_object() {
*obj = Value::Object(serde_json::Map::new());
}
if let Value::Object(map) = obj {
let first = parts[0];
let rest = &parts[1..].join(".");
let nested = map
.entry(first.to_string())
.or_insert_with(|| Value::Object(serde_json::Map::new()));
Self::set_nested(nested, rest, value);
}
}
fn remove_nested(obj: &mut Value, path: &str) {
let parts: Vec<&str> = path.split('.').collect();
if parts.is_empty() {
return;
}
if parts.len() == 1 {
if let Value::Object(map) = obj {
map.remove(parts[0]);
}
return;
}
if let Value::Object(map) = obj {
let first = parts[0];
let rest = &parts[1..].join(".");
if let Some(nested) = map.get_mut(first) {
Self::remove_nested(nested, rest);
}
}
}
}
impl MAIN {
pub fn init(data: Value) -> Result<()> {
APP::init(data)
}
pub fn get_repository() -> Option<Arc<RwLock<Value>>> {
APP::get_repository()
}
pub fn get<T: serde::de::DeserializeOwned>(path: &str) -> Option<T> {
APP::get(path)
}
pub fn get_string(path: &str) -> Option<String> {
APP::get_string(path)
}
pub fn get_int(path: &str) -> Option<i64> {
APP::get_int(path)
}
pub fn get_bool(path: &str) -> Option<bool> {
APP::get_bool(path)
}
pub fn get_or<T: serde::de::DeserializeOwned>(path: &str, default: T) -> T {
APP::get_or(path, default)
}
pub fn set<T: serde::Serialize>(path: &str, value: T) -> Result<()> {
APP::set(path, value)
}
pub fn remove(path: &str) -> Result<()> {
APP::remove(path)
}
pub fn has(path: &str) -> bool {
APP::has(path)
}
pub fn clear() -> Result<()> {
APP::clear()
}
pub fn is_initialized() -> bool {
APP::is_initialized()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_app_repository_operations() {
APP::init(json!({})).unwrap();
APP::set("site_name", "Test Site").unwrap();
APP::set("version", "1.0.0").unwrap();
APP::set("stats.users.count", 100).unwrap();
APP::set("features.enabled", true).unwrap();
assert_eq!(APP::get_string("site_name"), Some("Test Site".to_string()));
assert_eq!(APP::get_string("version"), Some("1.0.0".to_string()));
assert_eq!(APP::get_int("stats.users.count"), Some(100));
assert_eq!(APP::get_bool("features.enabled"), Some(true));
assert_eq!(APP::get_or("site_name", "Default".to_string()), "Test Site");
assert_eq!(
APP::get_or("non.existent", "default".to_string()),
"default"
);
assert!(APP::has("site_name"));
assert!(APP::has("stats.users.count"));
assert!(!APP::has("non.existent"));
APP::remove("features.enabled").unwrap();
assert!(!APP::has("features.enabled"));
assert_eq!(MAIN::get_string("site_name"), Some("Test Site".to_string()));
MAIN::set("alias_test", "works").unwrap();
assert_eq!(APP::get_string("alias_test"), Some("works".to_string()));
}
}