1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::ApiTag;
use crate::RadioBrowserAPI;
use std::fmt::Display;

use std::collections::HashMap;
use std::error::Error;

pub enum TagOrder {
    Name,
    StationCount,
}

impl Display for TagOrder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            TagOrder::Name => write!(f, "name"),
            TagOrder::StationCount => write!(f, "stationcount"),
        }
    }
}

#[derive(Clone, Debug)]
pub struct TagSearchBuilder {
    map: HashMap<String, String>,
    api: RadioBrowserAPI,
    filter: Option<String>,
}

impl TagSearchBuilder {
    pub fn new(api: RadioBrowserAPI) -> Self {
        TagSearchBuilder {
            api,
            map: HashMap::new(),
            filter: None,
        }
    }

    pub fn filter<P: AsRef<str>>(mut self, filter: P) -> Self {
        self.filter = Some(filter.as_ref().to_string());
        self
    }

    pub fn order(mut self, order: TagOrder) -> Self {
        self.map.insert(String::from("order"), order.to_string());
        self
    }

    pub fn reverse(mut self, reverse: bool) -> Self {
        self.map
            .insert(String::from("reverse"), reverse.to_string());
        self
    }

    pub fn offset<P: AsRef<str>>(mut self, offset: P) -> Self {
        self.map
            .insert(String::from("offset"), offset.as_ref().to_string());
        self
    }

    pub fn limit<P: AsRef<str>>(mut self, limit: P) -> Self {
        self.map
            .insert(String::from("limit"), limit.as_ref().to_string());
        self
    }

    pub fn hidebroken(mut self, hidebroken: bool) -> Self {
        self.map
            .insert(String::from("hidebroken"), hidebroken.to_string());
        self
    }

    pub async fn send(mut self) -> Result<Vec<ApiTag>, Box<dyn Error>> {
        if let Some(filter) = self.filter {
            Ok(self
                .api
                .send(format!("/json/tags/{}", filter), self.map)
                .await?)
        } else {
            Ok(self.api.send("/json/tags", self.map).await?)
        }
    }
}