use serde::{Deserialize, Serialize};
use crate::app::LoopMode;
use crate::library::Library;
const STATE_VERSION: u32 = 1;
const STATE_FILE: &str = "state.json";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlaybackState {
version: u32,
pub queue: Vec<String>,
pub now_playing: Option<usize>,
pub position_secs: u64,
pub loop_mode: LoopMode,
pub speed: f32,
pub volume: f32,
}
impl PlaybackState {
pub const fn new(
queue: Vec<String>,
now_playing: Option<usize>,
position_secs: u64,
loop_mode: LoopMode,
speed: f32,
volume: f32,
) -> Self {
Self {
version: STATE_VERSION,
queue,
now_playing,
position_secs,
loop_mode,
speed,
volume,
}
}
pub fn load() -> Option<Self> {
let path = Library::find_state_file(STATE_FILE)?;
let raw = std::fs::read_to_string(path).ok()?;
let state: Self = serde_json::from_str(&raw).ok()?;
(state.version == STATE_VERSION).then_some(state)
}
pub fn save(&self) -> anyhow::Result<()> {
let path = Library::place_state_file(STATE_FILE)?;
let tmp = path.with_extension("json.tmp");
std::fs::write(&tmp, serde_json::to_string_pretty(self)?)?;
std::fs::rename(&tmp, &path)?;
Ok(())
}
pub fn discard() {
if let Some(path) = Library::find_state_file(STATE_FILE) {
let _ = std::fs::remove_file(path);
}
}
}