use super::key_value;
use crate::{
analysis::total_playtime,
platform::prelude::*,
settings::{Color, Field, Gradient, SettingsDescription, Value},
timing::formatter::{Days, Regular, TimeFormatter},
Timer,
};
use core::fmt::Write;
use serde::{Deserialize, Serialize};
#[derive(Default, Clone)]
pub struct Component {
settings: Settings,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
pub background: Gradient,
pub display_two_rows: bool,
pub show_days: bool,
pub label_color: Option<Color>,
pub value_color: Option<Color>,
}
impl Default for Settings {
fn default() -> Self {
Self {
background: key_value::DEFAULT_GRADIENT,
display_two_rows: false,
show_days: true,
label_color: None,
value_color: None,
}
}
}
impl Component {
pub fn new() -> Self {
Default::default()
}
pub const fn with_settings(settings: Settings) -> Self {
Self { settings }
}
pub const fn settings(&self) -> &Settings {
&self.settings
}
pub fn settings_mut(&mut self) -> &mut Settings {
&mut self.settings
}
pub const fn name(&self) -> &'static str {
"Total Playtime"
}
pub fn update_state(&self, state: &mut key_value::State, timer: &Timer) {
let total_playtime = total_playtime::calculate(timer);
state.background = self.settings.background;
state.key_color = self.settings.label_color;
state.value_color = self.settings.value_color;
state.semantic_color = Default::default();
state.key.clear();
state.key.push_str("Total Playtime");
state.value.clear();
if self.settings.show_days {
let _ = write!(state.value, "{}", Days::new().format(total_playtime));
} else {
let _ = write!(state.value, "{}", Regular::new().format(total_playtime));
}
state.key_abbreviations.clear();
state.key_abbreviations.push("Playtime".into());
state.display_two_rows = self.settings.display_two_rows;
state.updates_frequently = timer.current_phase().is_running();
}
pub fn state(&self, timer: &Timer) -> key_value::State {
let mut state = Default::default();
self.update_state(&mut state, timer);
state
}
pub fn settings_description(&self) -> SettingsDescription {
SettingsDescription::with_fields(vec![
Field::new("Background".into(), self.settings.background.into()),
Field::new(
"Display 2 Rows".into(),
self.settings.display_two_rows.into(),
),
Field::new("Show Days (>24h)".into(), self.settings.show_days.into()),
Field::new("Label Color".into(), self.settings.label_color.into()),
Field::new("Value Color".into(), self.settings.value_color.into()),
])
}
pub fn set_value(&mut self, index: usize, value: Value) {
match index {
0 => self.settings.background = value.into(),
1 => self.settings.display_two_rows = value.into(),
2 => self.settings.show_days = value.into(),
3 => self.settings.label_color = value.into(),
4 => self.settings.value_color = value.into(),
_ => panic!("Unsupported Setting Index"),
}
}
}