use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::Icon;
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct GenreTitle {
pub title: Option<String>,
pub full_title: Option<String>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Genre {
pub id: Option<String>,
pub weight: Option<i64>,
pub composer_top: Option<bool>,
pub title: Option<String>,
pub titles: HashMap<String, GenreTitle>,
pub images: Option<Value>,
pub show_in_menu: Option<bool>,
pub show_in_regions: Vec<i64>,
pub hide_in_regions: Vec<i64>,
pub full_title: Option<String>,
pub url_part: Option<String>,
pub color: Option<String>,
pub radio_icon: Option<Icon>,
pub sub_genres: Vec<Genre>,
}
impl Genre {
#[must_use]
pub fn localized_title(&self, language: &str) -> Option<&str> {
self.titles
.get(language)
.and_then(|t| t.title.as_deref())
.or(self.title.as_deref())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn localized_titles_fall_back_to_the_default() {
let genre: Genre =
serde_json::from_str(r#"{"id":"rock","title":"Rock","titles":{"ru":{"title":"Рок"}}}"#)
.unwrap();
assert_eq!(genre.localized_title("ru"), Some("Рок"));
assert_eq!(genre.localized_title("de"), Some("Rock"));
assert_eq!(Genre::default().localized_title("ru"), None);
}
#[test]
fn sub_genres_nest_recursively() {
let genre: Genre = serde_json::from_str(
r#"{"id":"rock","subGenres":[{"id":"punk","subGenres":[{"id":"hardcore"}]}]}"#,
)
.unwrap();
assert_eq!(genre.sub_genres[0].id.as_deref(), Some("punk"));
assert_eq!(
genre.sub_genres[0].sub_genres[0].id.as_deref(),
Some("hardcore")
);
}
#[test]
fn genre_models_survive_an_empty_object() {
serde_json::from_str::<Genre>("{}").unwrap();
serde_json::from_str::<GenreTitle>("{}").unwrap();
}
}