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
//! Response types returned by client requests

use std::collections::HashMap;
use std::ops::Deref;

use crate::shared::ApiKeyScope;
use crate::types::{ApiKeyId, ChannelId, ClientDatabaseId, ClientId, ServerId};
use crate::{Decode, DecodeError, Error, ErrorKind};

/// A raw response of at least one [`Entry`].
#[derive(Clone, Debug)]
pub struct Response {
    entries: Vec<Entry>,
}

impl Deref for Response {
    type Target = [Entry];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.entries
    }
}

impl Decode for Response {
    type Error = Error;

    fn decode(buf: &[u8]) -> Result<Self, Self::Error> {
        let mut entries = Vec::new();

        for entry in buf.split(|b| *b == b'|') {
            let entry = Entry::decode(entry)?;
            entries.push(entry);
        }

        Ok(Self { entries })
    }
}

/// A single entry of key-value pairs.
#[derive(Clone, Debug)]
pub struct Entry {
    fields: HashMap<String, Option<String>>,
}

impl Entry {
    /// Returns `true` if the `Entry` contains the given `key`.
    #[inline]
    pub fn contains(&self, key: &str) -> bool {
        self.fields.contains_key(key)
    }

    /// Parses and returns the value of a given `key` as `T`.
    ///
    /// # Errors
    ///
    /// This function returns an [`Error`] if the requested `key` does not exist, contains no value
    /// or cannot be decoded into `T`.
    pub fn get<T>(&self, key: &str) -> Result<T, Error>
    where
        T: Decode,
        T::Error: Into<Error>,
    {
        let Some(value) = self.fields.get(key) else {
            return Err(Error(ErrorKind::NoField));
        };

        let Some(value) = value else {
            return Err(Error(ErrorKind::NoField));
        };

        T::decode(value.as_bytes()).map_err(|e| e.into())
    }
}

impl Decode for Entry {
    type Error = Error;

    fn decode(buf: &[u8]) -> Result<Self, Self::Error> {
        let mut entry = HashMap::new();

        // KV pairs separated by ' '.
        for item in buf.split(|c| *c == b' ') {
            let mut parts = item.splitn(2, |c| *c == b'=');

            let Some(key) = parts.next() else {
                return Err(Error(DecodeError::UnexpectedEof.into()));
            };

            let key = match std::str::from_utf8(key) {
                Ok(key) => key.to_owned(),
                Err(err) => return Err(Error(err.into())),
            };

            let value = match parts.next() {
                Some(value) => {
                    let value = match std::str::from_utf8(value) {
                        Ok(value) => value,
                        Err(err) => return Err(Error(err.into())),
                    };

                    Some(value.to_owned())
                }
                None => None,
            };

            entry.insert(key, value);
        }

        Ok(Self { fields: entry })
    }
}

/// Data returned from the `version` command.
#[derive(Debug, Decode, Default)]
pub struct Version {
    pub version: String,
    pub build: u64,
    pub platform: String,
    _priv: (),
}

/// An API Key returned from [`Client.apikeyadd`].
#[derive(Debug, Decode, Default)]
pub struct ApiKey {
    pub apikey: String,
    pub id: ApiKeyId,
    pub sid: ServerId,
    pub cldbid: ClientDatabaseId,
    pub scope: ApiKeyScope,
    pub time_left: u64,
    _priv: (),
}

#[derive(Clone, Debug, Default, Decode)]
pub struct Whoami {
    pub virtualserver_status: VirtualServerStatus,
    pub virtualserver_unique_identifier: String,
    pub virtualserver_port: u16,
    pub virtualserver_id: ServerId,
    pub client_id: ClientId,
    pub client_channel_id: ChannelId,
    pub client_nickname: String,
    pub client_database_id: ClientDatabaseId,
    pub client_login_name: String,
    pub client_unique_identifier: String,
    pub client_origin_server_id: ServerId,
    _priv: (),
}

#[derive(Copy, Clone, Debug, Default)]
pub enum VirtualServerStatus {
    #[default]
    Unknown,
    Online,
    Offline,
}

impl Decode for VirtualServerStatus {
    type Error = Error;

    fn decode(buf: &[u8]) -> Result<Self, Self::Error> {
        match buf {
            b"unknown" => Ok(Self::Unknown),
            b"online" => Ok(Self::Online),
            b"offline" => Ok(Self::Offline),
            _ => Err(Error(DecodeError::UnexpectedEof.into())),
        }
    }
}