use std::fs;
use std::path::PathBuf;
use super::models::AppState;
pub struct ConfigManager {
config_path: PathBuf,
}
impl ConfigManager {
pub fn new() -> Self {
let config_path = Self::get_config_path();
Self { config_path }
}
pub fn get_config_path() -> PathBuf {
let mut path = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("iris");
fs::create_dir_all(&path).ok();
path.push("config.json");
path
}
pub fn path(&self) -> &PathBuf {
&self.config_path
}
pub fn load(&self) -> AppState {
if self.config_path.exists() {
if let Ok(content) = fs::read_to_string(&self.config_path) {
if let Ok(state) = serde_json::from_str(&content) {
return state;
}
}
}
AppState::default()
}
pub fn save(&self, state: &AppState) -> Result<(), String> {
match serde_json::to_string_pretty(state) {
Ok(json) => {
fs::write(&self.config_path, json)
.map_err(|e| format!("Erro ao salvar configurações: {}", e))
}
Err(e) => Err(format!("Erro ao serializar configurações: {}", e)),
}
}
pub fn export(&self, state: &AppState, path: &PathBuf) -> Result<(), String> {
match serde_json::to_string_pretty(state) {
Ok(json) => {
fs::write(path, json)
.map_err(|e| format!("Erro ao exportar configurações: {}", e))
}
Err(e) => Err(format!("Erro ao serializar configurações: {}", e)),
}
}
pub fn import(&self, path: &PathBuf) -> Result<AppState, String> {
let content = fs::read_to_string(path)
.map_err(|e| format!("Erro ao ler arquivo: {}", e))?;
let mut state: AppState = serde_json::from_str(&content)
.map_err(|e| format!("Erro ao processar JSON: {}", e))?;
for app in &mut state.apps {
app.id = crate::utils::uuid_simple();
}
Ok(state)
}
}
impl Default for ConfigManager {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_path_exists() {
let path = ConfigManager::get_config_path();
assert!(path.to_string_lossy().contains("iris"));
}
#[test]
fn test_default_state_is_empty() {
let state = AppState::default();
assert!(state.apps.is_empty());
}
}