use crate::types::BotOption;
use puniyu_common::read_config;
use puniyu_path::config_dir;
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::{collections::HashMap, path::PathBuf, sync::LazyLock};
static CONFIG_PATH: LazyLock<PathBuf> = LazyLock::new(|| config_dir().join("bot.toml"));
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct BotConfig {
#[serde(default)]
global: BotOption,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
bot: HashMap<SmolStr, BotOption>,
}
impl BotConfig {
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(), "bot").unwrap_or_default(),
)
}
pub fn global(&self) -> &BotOption {
&self.global
}
pub fn bot(&self, bot_id: &str) -> BotOption {
self.bot
.get(bot_id)
.map(|specific| crate::common::MergeWith::merge_with(specific, &self.global))
.unwrap_or_else(|| self.global.clone())
}
pub fn list(&self) -> HashMap<&str, BotOption> {
self.bot
.iter()
.map(|(id, specific)| {
(id.as_str(), crate::common::MergeWith::merge_with(specific, &self.global))
})
.collect()
}
}
impl crate::Config for BotConfig {
fn name(&self) -> &str {
"bot"
}
#[inline]
fn to_value(&self) -> toml::Value {
crate::serialize_to_value(self)
}
}