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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use crate::api_core::endpoints::access_management::GetServicesResponse;
use crate::api_core::endpoints::access_management::{
    SERVICE_TYPE_ALL_KNOWN_FILES, SERVICE_TYPE_ALL_KNOWN_TAGS, SERVICE_TYPE_ALL_LOCAL_FILES,
    SERVICE_TYPE_FILE_REPOSITORIES, SERVICE_TYPE_LOCAL_FILES, SERVICE_TYPE_LOCAL_TAGS,
    SERVICE_TYPE_TAG_REPOSITORIES, SERVICE_TYPE_TRASH,
};

use crate::api_core::common::ServiceIdentifier;
use crate::error::Error;
use crate::wrapper::builders::search_builder::SearchBuilder;
use crate::Client;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter};

#[derive(Clone, PartialOrd, PartialEq, Hash)]
pub enum ServiceType {
    LocalTags,
    TagRepositories,
    LocalFiles,
    FileRepositories,
    AllLocalFiles,
    AllKnownFiles,
    AllKnownTags,
    Trash,
}

impl Eq for ServiceType {}

impl TryFrom<String> for ServiceType {
    type Error = Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.as_str() {
            s if s == SERVICE_TYPE_LOCAL_TAGS => Ok(Self::LocalTags),
            s if s == SERVICE_TYPE_TAG_REPOSITORIES => Ok(Self::TagRepositories),
            s if s == SERVICE_TYPE_LOCAL_FILES => Ok(Self::LocalFiles),
            s if s == SERVICE_TYPE_FILE_REPOSITORIES => Ok(Self::FileRepositories),
            s if s == SERVICE_TYPE_ALL_LOCAL_FILES => Ok(Self::AllLocalFiles),
            s if s == SERVICE_TYPE_ALL_KNOWN_FILES => Ok(Self::AllKnownFiles),
            s if s == SERVICE_TYPE_ALL_KNOWN_TAGS => Ok(Self::AllKnownTags),
            s if s == SERVICE_TYPE_TRASH => Ok(Self::Trash),
            _ => Err(Error::InvalidServiceType(value)),
        }
    }
}

impl ToString for ServiceType {
    fn to_string(&self) -> String {
        match self {
            ServiceType::LocalTags => String::from(SERVICE_TYPE_LOCAL_TAGS),
            ServiceType::TagRepositories => String::from(SERVICE_TYPE_TAG_REPOSITORIES),
            ServiceType::LocalFiles => String::from(SERVICE_TYPE_LOCAL_FILES),
            ServiceType::FileRepositories => String::from(SERVICE_TYPE_FILE_REPOSITORIES),
            ServiceType::AllLocalFiles => String::from(SERVICE_TYPE_ALL_LOCAL_FILES),
            ServiceType::AllKnownFiles => String::from(SERVICE_TYPE_ALL_KNOWN_FILES),
            ServiceType::AllKnownTags => String::from(SERVICE_TYPE_ALL_KNOWN_TAGS),
            ServiceType::Trash => String::from(SERVICE_TYPE_TRASH),
        }
    }
}

#[derive(Clone, PartialOrd, PartialEq, Hash)]
pub struct ServiceName(pub String);

impl Eq for ServiceName {}

impl ServiceName {
    pub fn my_tags() -> Self {
        Self(String::from("my tags"))
    }

    pub fn my_files() -> Self {
        Self(String::from("my files"))
    }

    pub fn public_tag_repository() -> Self {
        Self(String::from("public tag repository"))
    }

    pub fn all_local_files() -> Self {
        Self(String::from("all local files"))
    }

    pub fn all_known_tags() -> Self {
        Self(String::from("all known tags"))
    }

    pub fn all_known_files() -> Self {
        Self(String::from("all known files"))
    }
}

impl Display for ServiceName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl Into<ServiceIdentifier> for ServiceName {
    fn into(self) -> ServiceIdentifier {
        ServiceIdentifier::Name(self.0)
    }
}

#[derive(Clone)]
pub struct Service {
    client: Client,
    pub name: ServiceName,
    pub key: String,
    pub service_type: ServiceType,
}

impl Service {
    pub fn search(&self) -> SearchBuilder {
        let builder = SearchBuilder::new(self.client.clone());
        match self.service_type {
            ServiceType::LocalTags | ServiceType::TagRepositories | ServiceType::AllKnownTags => {
                builder.tag_service_key(&self.key)
            }
            ServiceType::LocalFiles
            | ServiceType::FileRepositories
            | ServiceType::AllLocalFiles
            | ServiceType::AllKnownFiles
            | ServiceType::Trash => builder.file_service_key(&self.key),
        }
    }
}

#[derive(Clone)]
pub struct Services {
    inner: HashMap<ServiceType, Vec<Service>>,
}

impl Services {
    /// Creates the services list from a given hydrus response
    pub fn from_response(client: Client, response: GetServicesResponse) -> Self {
        let mut response = response.other;
        let mut mapped_types = HashMap::with_capacity(response.keys().len());
        let keys = response.keys().cloned().collect::<Vec<String>>().clone();

        for service_type in &keys {
            if let Ok(mapped_type) = ServiceType::try_from(service_type.clone()) {
                let basic_services = response.remove(service_type).unwrap();
                let mut service_list = Vec::new();

                for basic_service in basic_services {
                    service_list.push(Service {
                        service_type: mapped_type.clone(),
                        name: ServiceName(basic_service.name),
                        key: basic_service.service_key,
                        client: client.clone(),
                    })
                }

                mapped_types.insert(mapped_type, service_list);
            }
        }

        Self {
            inner: mapped_types,
        }
    }

    /// Returns a list of all services of the given type
    pub fn get_services(&self, service_type: ServiceType) -> Vec<&Service> {
        if let Some(services) = self.inner.get(&service_type) {
            services.into_iter().collect()
        } else {
            Vec::new()
        }
    }
}