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
use thiserror::Error;
use crate::formats::EbookError;

pub(crate) trait Readable {
    // Reader navigation using a string
    fn navigate_str(&self, path: &str) -> Result<usize, ReaderError>;
    // Reader navigation using an index
    fn navigate(&self, index: usize) -> Result<String, ReaderError>;
}

/// Possible errors for [Reader](Reader)
/// - **OutOfBounds**: When a given index exceeds the reader's bounds.
/// - **InvalidReference**: When the reader fails to retrieve content
/// due to lack of proper references. Usually caused by malformed files.
/// - **NoContent**: When retrieval of content to display fails.
#[derive(Error, Debug)]
pub enum ReaderError {
    #[error("[OutOfBounds Error][{cause}]: {description}")]
    OutOfBounds { cause: String, description: String },
    #[error("[InvalidReference Error][{cause}]: {description}")]
    InvalidReference { cause: String, description: String },
    #[error("[NoContent Error]{0}")]
    NoContent(EbookError)
}

/// Reader that allows traversal of an ebook file by file
///
/// # Examples
/// Opening and reading an epub file:
/// ```
/// use rbook::Ebook;
///
/// let epub = rbook::Epub::new("tests/ebooks/moby-dick.epub").unwrap();
///
/// // Creating a reader instance
/// let mut reader = epub.reader();
///
/// assert_eq!(0, reader.current_index());
///
/// // Printing the contents of each page
/// while let Some(content) = reader.next_page() {
///     println!("{content}")
/// }
///
/// assert_eq!(143, reader.current_index());
/// ```
/// Traversing and retrieving pages from a reader:
/// ```
/// # use rbook::Ebook;
/// # let epub = rbook::Epub::new("tests/ebooks/moby-dick.epub").unwrap();
/// let mut reader = epub.reader();
///
/// // Set reader position using an index or string
/// let content1 = reader.set_current_page(56).unwrap();
/// let content2 = reader.set_current_page_str("chapter_051.xhtml").unwrap();
///
/// assert_eq!(content1, content2);
///
/// // Get a page without updating the reader index
/// let content1 = reader.fetch_page(1).unwrap();
/// let content2 = reader.fetch_page_str("titlepage.xhtml").unwrap();
///
/// assert_eq!(56, reader.current_index());
/// assert_eq!(content1, content2);
/// ```
pub struct Reader<'a> {
    ebook: &'a dyn Readable,
    page_count: usize,
    current_index: usize,
}

impl<'a> Reader<'a> {
    // TODO: Potentially remove the page count argument here...
    pub(crate) fn new(ebook: &'a dyn Readable, page_count: usize) -> Self {
        Self {
            ebook,
            page_count,
            current_index: 0,
        }
    }

    pub fn current_index(&self) -> usize {
        self.current_index
    }

    /// Retrieve the count of pages that can be traversed.
    ///
    /// The maximum value of the reader index is `page_count - 1`,
    /// similar to an array.
    pub fn page_count(&self) -> usize {
        self.page_count
    }

    /// Retrieve the page content of where the reader's
    /// current index is at
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn current_page(&self) -> Result<String, ReaderError> {
        self.fetch_page(self.current_index)
    }

    /// Retrieve the next page content. If retrieving the next page
    /// results in an error. The next page after it will be
    /// retrieved instead and so on.
    ///
    /// To view and handle errors, [try_previous_page()](Reader::try_next_page) can be used
    /// instead.
    pub fn next_page(&mut self) -> Option<String> {
        while self.current_index < self.page_count - 1 {
            match self.try_next_page() {
                Ok(page_content) => return Some(page_content),
                _ => self.current_index += 1,
            }
        }

        None
    }

    /// Retrieve the previous page content. If retrieving the previous page
    /// results in an error. The previous page before it will be
    /// retrieved instead and so on.
    ///
    /// To view and handle errors, [try_previous_page()](Reader::try_previous_page) can be used
    /// instead.
    pub fn previous_page(&mut self) -> Option<String> {
        while self.current_index > 0 {
            match self.try_previous_page() {
                Ok(page_content) => return Some(page_content),
                _ => self.current_index -= 1,
            }
        }

        None
    }

    /// Retrieve the next page content. If an error is encountered,
    /// the index is not updated.
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn try_next_page(&mut self) -> Result<String, ReaderError> {
        self.set_current_page(self.current_index + 1)
    }

    /// Retrieve the previous page content. If an error is encountered,
    /// the index is not updated.
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn try_previous_page(&mut self) -> Result<String, ReaderError> {
        self.set_current_page(self.current_index - 1)
    }

    /// Retrieve the content of a page and update the
    /// reader's current index.
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn set_current_page(&mut self, page_index: usize) -> Result<String, ReaderError> {
        match self.fetch_page(page_index) {
            Ok(page_content) => {
                self.current_index = page_index;
                Ok(page_content)
            }
            Err(error) => Err(error)
        }
    }

    /// Retrieve the content of a page and update the
    /// reader's current index using a string value.
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn set_current_page_str(&mut self, path: &str) -> Result<String, ReaderError> {
        match self.ebook.navigate_str(path) {
            Ok(index) => self.set_current_page(index),
            Err(error) => Err(error)
        }
    }

    /// Retrieve the content of a page without updating the
    /// reader's current index.
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn fetch_page(&self, page_index: usize) -> Result<String, ReaderError> {
        self.ebook.navigate(page_index)
    }

    /// Retrieve the content of a page without updating the
    /// reader's current index using a string value.
    ///
    /// # Errors
    /// Possible errors are described in [ReaderError](ReaderError).
    pub fn fetch_page_str(&self, path: &str) -> Result<String, ReaderError> {
        match self.ebook.navigate_str(path) {
            Ok(index) => self.fetch_page(index),
            Err(error) => Err(error)
        }
    }
}