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
//! Dynasty reader's directory.

pub mod sample;

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::{Tag, TagKind};

/// Dynasty reader's directory listing.
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct DirectoryListing {
    /// The directory's tags.
    pub tags: Vec<Tag>,
    /// The directory's current page.
    pub current_page: u16,
    /// The directory's total pages.
    pub total_pages: u16,
}

impl DirectoryListing {
    pub(crate) fn from_raw(raw: DirectoryRaw, kind: TagKind) -> DirectoryListing {
        let DirectoryRaw {
            tags,
            current_page,
            total_pages,
        } = raw;

        let tags = tags
            .into_iter()
            .flat_map(|tag| tag.into_values())
            .flatten()
            .map(|directory_tag| directory_tag.into_tag(kind))
            .collect();

        DirectoryListing {
            tags,
            current_page,
            total_pages,
        }
    }

    /// Helper method to extend [`DirectoryListing`] `tags` with another [`DirectoryListing`] `tags`.
    pub fn extend(&mut self, other: DirectoryListing) {
        let DirectoryListing { tags, .. } = other;
        self.tags.extend(tags)
    }

    /// Helper method to get the next page number.
    pub fn next_page(&self) -> Option<u16> {
        if self.total_pages > self.current_page {
            Some(self.current_page + 1)
        } else {
            None
        }
    }
}

#[derive(Debug, Deserialize)]
pub(crate) struct DirectoryRaw {
    tags: Vec<HashMap<String, Vec<DirectoryTag>>>,
    current_page: u16,
    total_pages: u16,
}

#[derive(Debug, Deserialize)]
pub(crate) struct DirectoryTag {
    #[serde(rename(deserialize = "name"))]
    title: String,
    permalink: String,
}

impl DirectoryTag {
    pub fn into_tag(self, kind: TagKind) -> Tag {
        let DirectoryTag { title, permalink } = self;
        Tag {
            kind,
            title,
            permalink,
        }
    }
}