use crate::ui::Loop;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::fs::{self, read_to_string};
use std::path::PathBuf;
pub const MUSIC_DIR: &str = "~/Music";
#[derive(Clone, Deserialize, Serialize)]
pub struct Termusic {
pub music_dir: String,
#[serde(skip_serializing)]
pub music_dir_from_cli: Option<String>,
pub loop_mode: Loop,
pub volume: i32,
pub add_playlist_front: bool,
}
impl Default for Termusic {
fn default() -> Self {
Self {
music_dir: MUSIC_DIR.to_string(),
music_dir_from_cli: None,
loop_mode: Loop::Queue,
volume: 70,
add_playlist_front: false,
}
}
}
impl Termusic {
pub fn save(&self) -> Result<()> {
let mut path = get_app_config_path()?;
path.push("config.toml");
let string = toml::to_string(self)?;
fs::write(path.to_string_lossy().as_ref(), string)?;
Ok(())
}
pub fn load(&mut self) -> Result<()> {
let mut path = get_app_config_path()?;
path.push("config.toml");
if !path.exists() {
let config = Self::default();
config.save()?;
}
let string = read_to_string(path.to_string_lossy().as_ref())?;
let config: Self = toml::from_str(&string)?;
*self = config;
Ok(())
}
}
pub fn get_app_config_path() -> Result<PathBuf> {
let mut path =
dirs_next::config_dir().ok_or_else(|| anyhow!("failed to find os config dir."))?;
path.push("termusic");
if !path.exists() {
fs::create_dir_all(&path)?;
}
Ok(path)
}