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
use std::error;
use std::fmt::{Display, Debug};
use std::fs;
use colored::Colorize;
pub type Result<T> = std::result::Result<T, self::Error>;



#[derive(Clone)]
pub struct Error {
    kind: ErrorKind,
    error: String
}
#[derive(Clone)]
pub enum ErrorKind {
    PathNotSpecified,
    FileNotFound,
    EmptyContent,
    MultipleFlags
}

impl Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            ErrorKind::PathNotSpecified => write!(f, "\n{}\nThe path attribute is empty!\n{}", "Path not specified".red().bold(),self.error),
            ErrorKind::FileNotFound => write!(f, "\n{}\nDidn't found any file\n{}", "File not found".red().bold(), self.error), 
            ErrorKind::EmptyContent => write!(f, "\n{}\nYou didn't get the content from the file, invoque the `get_content()` method\n{}", "Empty content".red().bold(), self.error),
            ErrorKind::MultipleFlags => write!(f, "\n{}\nCan't use more than one flag\n{}", "Multiple flags".red().bold(), self.error),
        }
    }
}
impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            ErrorKind::PathNotSpecified => write!(f, "The path attribute is empty!"),
            ErrorKind::FileNotFound => write!(f, "Didn't found any file"), 
            ErrorKind::EmptyContent => write!(f, "You didn't get the content from the file, invoque the `get_content()` method"),
            ErrorKind::MultipleFlags => write!(f, "Can't use more than one flag"),
        }
    }
}
impl std::error::Error for Error {
    fn cause(&self) -> Option<&dyn error::Error> {
        Some(self)
    }
}



#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct File {
    path: Option<String>,
    content: Option<String>
}
impl Default for File {
    fn default() -> Self {
        Self::new()
    }
}
impl Display for File {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let file = self.clone();
        if let Some(path) = file.path {
            if let Some(content) = file.content {
                return write!(f, "\nThe file {} has the following content:\n\n {}", path.bold(), content);
            }
            return write!(f, "\nThe file has the {} path, but has no content", path.bold());
        }
        write!(f, "\nThe file has no path")
    }
}
impl File {
    /// Creates a new File
    pub fn new() -> Self {
        File { path: None, content: None }
    }
    /// Same as new but with a path setted from the beginning
    pub fn from_path(path: String) -> Self {
        File { path: Some(path), content: None }
    }
    pub fn set_path(&mut self, path: String) {
        self.path = Some(path);
    }
    /// Gets the content from the specified file and introduces it as a String in the content attribute
    /// Returns a result in case the file name doesn't exist or the path attribute is empty
    pub fn get_content(&mut self) -> Result<()> {
        match self.path.clone() {
            Some(path) => {match  fs::read_to_string(path.as_str()) {
                    Ok(content) => {
                        self.content = Some(content);
                        Ok(())
                    },
                    Err(_)=> Err(Error { kind: ErrorKind::FileNotFound, error: format!("Ensure you introduce a correct path.\n\n{} If you use Tab it can help you autocomplete the name of the file.\n", "Hint:".bold().black().on_bright_white()) }),
                }
            },
            None => Err(Error { kind: ErrorKind::PathNotSpecified, error: format!("You must specify a path in order to get the content.\n\n{} Use the `set_path()` method or create with the `from_path()` method.\n", "Hint:".bold().black().on_bright_white())})

        }
        
    }
    /// Prints the content as is
    pub fn print_content(&self) -> Result<String> {
        match self.content.as_deref() {
            Some(cont) => {
                Ok(cont.to_string())
            },
            None => Err(Error { kind: ErrorKind::EmptyContent, error: format!("The file has no content.\n\n{} Execute the `get_content()` method first\n", "Hint:".bold().black().on_white())})
        }
    }
    /// Prints the content reversing both lines and characters
    pub fn print_reverse(&self) -> Result<String> {
        match self.content.as_deref() {
            Some(cont) => { 
                Ok(cont.chars().rev().collect::<String>())
            },
            None => Err(Error { kind: ErrorKind::EmptyContent, error: format!("The file has no content.\n\n{} Execute the `get_content()` method first\n", "Hint:".bold().black().on_white())})
        }
    }
    /// Prints the content reversing only the lines
    pub fn print_lines_reverse(&self) -> Result<String> {
        match self.content.as_deref() {
            Some(cont) => {
                Ok(cont.split('\n').collect::<Vec<&str>>().iter().rev().copied().collect::<Vec<&str>>().join("\n"))
            },
            None => Err(Error { kind: ErrorKind::EmptyContent, error: format!("The file has no content.\n\n{} Execute the `get_content()` method first\n", "Hint:".bold().black().on_white())})
        }
    }
    /// Prints the content reversing only the characters within the lines
    pub fn print_chars_reverse(&self) -> Result<String> {
        match self.content.as_deref() {
            Some(cont) => {
                Ok(cont.split('\n').collect::<Vec<&str>>().iter().map(|line| {
                    line.chars().rev().collect::<String>()
                }).collect::<Vec<String>>().join("\n"))
            },
            None => Err(Error { kind: ErrorKind::EmptyContent, error: format!("The file has no content.\n\n{} Execute the `get_content()` method first\n", "Hint:".bold().black().on_white())})
        }
    }
}
pub fn get_file_and_print(args: (String, bool, bool, bool)) -> Result<()> {
    let mut file = File::from_path(args.0);
    file.get_content()?;
    let mut content_to_print = String::new();
    match (args.1, args.2, args.3) {
        (false, false, false) => content_to_print = file.print_content()?,
        (true, false, false) => content_to_print = file.print_reverse()?,
        (false, true, false) => content_to_print = file.print_lines_reverse()?,
        (false, false, true) => content_to_print = file.print_chars_reverse()?,
        _ => Err(Error  { kind: ErrorKind::MultipleFlags, error: format!("\n\n{} Use a single flag\n", "Hint:".bold().black().on_white())})?,
    }
    println!("\n{}\n", content_to_print);
    Ok(())
}







#[cfg(test)]
mod tests {
    use crate::File;
    #[test]
    #[should_panic]
    fn print_content_test_empty_content() {
        let file = File::new();
        file.print_content().unwrap();
    }
    #[test]
    fn print_content_with_content() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!"))
        };
        assert_eq!(file.print_content().unwrap(), String::from("Hello there!"))
    }
    #[test]
    fn print_content_with_content_intros() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\n!ereht olleH"))
        };
        assert_eq!(file.print_content().unwrap(), String::from("Hello there!\n!ereht olleH"))
    }
    #[test]
    #[should_panic]
    fn print_reverse_empty() {
        let file = File::new();
        file.print_reverse().unwrap();
    }
    #[test]
    #[should_panic]
    fn print_reverse_panic() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\nGeneral Kenobi"))
        };
        assert_eq!(file.print_reverse().unwrap(), String::from("Hello there!\nGeneral Kenobi"));
    }
    #[test]
    fn print_reverse() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\nGeneral Kenobi"))
        };
        assert_eq!(file.print_reverse().unwrap(), String::from("iboneK lareneG\n!ereht olleH"));
    }
    #[test]
    #[should_panic]
    fn print_lines_reverse_empty() {
        let file = File::new();
        file.print_lines_reverse().unwrap();
    }
    #[test]
    #[should_panic]
    fn print_lines_reverse_panic() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\nGeneral Kenobi"))
        };
        assert_eq!(file.print_lines_reverse().unwrap(), String::from("Hello there!\nGeneral Kenobi"));
    }
    #[test]
    fn print_lines_reverse() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\nGeneral Kenobi"))
        };
        assert_eq!(file.print_lines_reverse().unwrap(), String::from("General Kenobi\nHello there!"));
    }
    #[test]
    #[should_panic]
    fn print_characters_reverse_empty() {
        let file = File::new();
        file.print_chars_reverse().unwrap();
    }
    #[test]
    #[should_panic]
    fn print_characters_reverse_panic() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\nGeneral Kenobi"))
        };
        assert_eq!(file.print_chars_reverse().unwrap(), String::from("Hello there!\nGeneral Kenobi"));
    }
    #[test]
    fn print_chars_reverse() {
        let file = File {
            path: Some(String::new()),
            content: Some(String::from("Hello there!\nGeneral Kenobi"))
        };
        assert_eq!(file.print_chars_reverse().unwrap(), String::from("!ereht olleH\niboneK lareneG"));
    }
}