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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{
    de::{self, MapAccess, Visitor},
    Deserialize, Deserializer,
};

use torn_api_macros::ApiCategory;

use crate::user;

#[derive(Debug, Clone, Copy, ApiCategory)]
#[api(category = "torn")]
#[non_exhaustive]
pub enum TornSelection {
    #[api(
        field = "competition",
        with = "decode_competition",
        type = "Option<Competition>"
    )]
    Competition,

    #[api(type = "HashMap<String, TerritoryWar>", field = "territorywars")]
    TerritoryWars,

    #[api(type = "HashMap<String, Racket>", field = "rackets")]
    Rackets,

    #[api(
        type = "HashMap<String, Territory>",
        with = "decode_territory",
        field = "territory"
    )]
    Territory,

    #[api(type = "TerritoryWarReport", field = "territorywarreport")]
    TerritoryWarReport,
}

pub type Selection = TornSelection;

#[derive(Debug, Clone, Deserialize)]
pub struct EliminationLeaderboard {
    pub position: i16,
    pub team: user::EliminationTeam,
    pub score: i16,
    pub lives: i16,
    pub participants: Option<i16>,
    pub wins: Option<i32>,
    pub losses: Option<i32>,
}

#[derive(Debug, Clone)]
pub enum Competition {
    Elimination { teams: Vec<EliminationLeaderboard> },
    Unkown(String),
}

fn decode_competition<'de, D>(deserializer: D) -> Result<Option<Competition>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct CompetitionVisitor;

    impl<'de> Visitor<'de> for CompetitionVisitor {
        type Value = Option<Competition>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("struct Competition")
        }

        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            deserializer.deserialize_map(self)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
        where
            V: MapAccess<'de>,
        {
            let mut name = None;
            let mut teams = None;

            while let Some(key) = map.next_key()? {
                match key {
                    "name" => {
                        name = Some(map.next_value()?);
                    }
                    "teams" => {
                        teams = Some(map.next_value()?);
                    }
                    _ => (),
                };
            }

            let name = name.ok_or_else(|| de::Error::missing_field("name"))?;

            match name {
                "Elimination" => Ok(Some(Competition::Elimination {
                    teams: teams.ok_or_else(|| de::Error::missing_field("teams"))?,
                })),
                "" => Ok(None),
                v => Ok(Some(Competition::Unkown(v.to_owned()))),
            }
        }
    }

    deserializer.deserialize_option(CompetitionVisitor)
}

#[derive(Debug, Clone, Deserialize)]
pub struct TerritoryWar {
    pub territory_war_id: i32,
    pub assaulting_faction: i32,
    pub defending_faction: i32,

    #[serde(with = "chrono::serde::ts_seconds")]
    pub started: DateTime<Utc>,
    #[serde(with = "chrono::serde::ts_seconds")]
    pub ends: DateTime<Utc>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Racket {
    pub name: String,
    pub level: i16,
    pub reward: String,

    #[serde(with = "chrono::serde::ts_seconds")]
    pub created: DateTime<Utc>,
    #[serde(with = "chrono::serde::ts_seconds")]
    pub changed: DateTime<Utc>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Territory {
    pub sector: i16,
    pub size: i16,
    pub slots: i16,
    pub daily_respect: i16,
    pub faction: i32,

    pub neighbors: Vec<String>,
    pub war: Option<TerritoryWar>,
    pub racket: Option<Racket>,
}

fn decode_territory<'de, D>(deserializer: D) -> Result<HashMap<String, Territory>, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
}

#[derive(Clone, Debug, Deserialize)]
pub struct TerritoryWarReportTerritory {
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerritoryWarOutcome {
    EndWithPeaceTreaty,
    EndWithDestroyDefense,
    FailAssault,
    SuccessAssault,
}

#[derive(Clone, Debug, Deserialize)]
pub struct TerritoryWarReportWar {
    #[serde(with = "chrono::serde::ts_seconds")]
    pub start: DateTime<Utc>,
    #[serde(with = "chrono::serde::ts_seconds")]
    pub end: DateTime<Utc>,

    pub result: TerritoryWarOutcome,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerritoryWarReportRole {
    Aggressor,
    Defender,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TerritoryWarReportFaction {
    pub name: String,
    pub score: i32,
    pub joins: i32,
    pub clears: i32,
    #[serde(rename = "type")]
    pub role: TerritoryWarReportRole,
}

#[derive(Clone, Debug, Deserialize)]
pub struct TerritoryWarReport {
    pub territory: TerritoryWarReportTerritory,
    pub war: TerritoryWarReportWar,
    pub factions: HashMap<i32, TerritoryWarReportFaction>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::{async_test, setup, Client, ClientTrait};

    #[async_test]
    async fn competition() {
        let key = setup();

        let response = Client::default()
            .torn_api(key)
            .torn(|b| {
                b.selections([
                    TornSelection::Competition,
                    TornSelection::TerritoryWars,
                    TornSelection::Rackets,
                ])
            })
            .await
            .unwrap();

        response.competition().unwrap();
        response.territory_wars().unwrap();
        response.rackets().unwrap();
    }

    #[async_test]
    async fn territory() {
        let key = setup();

        let response = Client::default()
            .torn_api(key)
            .torn(|b| b.selections([Selection::Territory]).id("NSC"))
            .await
            .unwrap();

        let territory = response.territory().unwrap();
        assert!(territory.contains_key("NSC"));
    }

    #[async_test]
    async fn invalid_territory() {
        let key = setup();

        let response = Client::default()
            .torn_api(key)
            .torn(|b| b.selections([Selection::Territory]).id("AAA"))
            .await
            .unwrap();

        assert!(response.territory().unwrap().is_empty());
    }

    #[async_test]
    async fn territory_war_report() {
        let key = setup();

        let response = Client::default()
            .torn_api(&key)
            .torn(|b| b.selections([Selection::TerritoryWarReport]).id(37403))
            .await
            .unwrap();

        assert_eq!(
            response.territory_war_report().unwrap().war.result,
            TerritoryWarOutcome::SuccessAssault
        );

        let response = Client::default()
            .torn_api(&key)
            .torn(|b| b.selections([Selection::TerritoryWarReport]).id(37502))
            .await
            .unwrap();

        assert_eq!(
            response.territory_war_report().unwrap().war.result,
            TerritoryWarOutcome::FailAssault
        );

        let response = Client::default()
            .torn_api(&key)
            .torn(|b| b.selections([Selection::TerritoryWarReport]).id(37860))
            .await
            .unwrap();

        assert_eq!(
            response.territory_war_report().unwrap().war.result,
            TerritoryWarOutcome::EndWithPeaceTreaty
        );

        let response = Client::default()
            .torn_api(&key)
            .torn(|b| b.selections([Selection::TerritoryWarReport]).id(23757))
            .await
            .unwrap();

        assert_eq!(
            response.territory_war_report().unwrap().war.result,
            TerritoryWarOutcome::EndWithDestroyDefense
        );
    }
}