use crate::types::GroupOption;
use puniyu_common::read_config;
use puniyu_path::config_dir;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, path::PathBuf, sync::LazyLock};
static CONFIG_PATH: LazyLock<PathBuf> = LazyLock::new(|| config_dir().join("group.toml"));
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GroupConfig {
#[serde(default)]
global: GroupOption,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
group: HashMap<String, GroupOption>,
}
impl GroupConfig {
pub fn get() -> Self {
use crate::ConfigRegistry;
ConfigRegistry::get(CONFIG_PATH.as_path()).and_then(|v| v.try_into().ok()).unwrap_or_else(
|| read_config::<Self>(config_dir().as_path(), "group").unwrap_or_default(),
)
}
pub fn global(&self) -> &GroupOption {
&self.global
}
pub fn group(&self, group_id: &str) -> GroupOption {
self.group
.get(group_id)
.map(|specific| crate::common::MergeWith::merge_with(specific, &self.global))
.unwrap_or_else(|| self.global.clone())
}
pub fn list(&self) -> Vec<GroupOption> {
self.group
.values()
.map(|specific| crate::common::MergeWith::merge_with(specific, &self.global))
.collect()
}
}
impl crate::Config for GroupConfig {
fn name(&self) -> &str {
"group"
}
fn to_value(&self) -> toml::Value {
crate::serialize_to_value(self)
}
}