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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use std::fmt::Display;
use std::io;
use std::io::prelude::*;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::Duration;

use crate::formatter::{colorize_string, Ansi, Formatter};
use crate::output;

#[allow(missing_docs)]
pub struct Logger<'a> {
    is_loading: Arc<RwLock<bool>>,
    loading_handle: Option<thread::JoinHandle<()>>,

    line_ending: String,
    formatter: Formatter<'a>,
}

impl<'a> Default for Logger<'a> {
    fn default() -> Self {
        Self {
            is_loading: Arc::new(RwLock::new(false)),
            loading_handle: None,

            line_ending: String::from("\n"),
            formatter: Formatter::new(),
        }
    }
}

impl<'a> Logger<'a> {
    /// Initializes a new logger
    ///
    /// # Example
    /// ```
    /// use paris::Logger;
    /// let logger = Logger::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Prints to stdout with no bells and whistles. I does however
    /// add a timestamp if enabled.
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// let mut logger = Logger::new();
    ///
    /// logger.log("Basic and boring."); // Basic and boring.
    /// ```
    ///
    /// Equivalent macro: `log!()`
    pub fn log<T: Display>(&mut self, message: T) -> &mut Self {
        self.stdout(message)
    }

    /// Prints to stdout and adds some info flair to the text
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    /// logger.info("This is some info");
    /// ```
    ///
    /// Equivalent macro: `info!()`
    pub fn info<T: Display>(&mut self, message: T) -> &mut Self {
        self.stdout(format!("<cyan><info></> {}", message))
    }

    /// Prints to stdout and adds some success flair to text
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    /// logger.success("Everything went great!");
    /// ```
    ///
    /// Equivalent macro: `success!()`
    pub fn success<T: Display>(&mut self, message: T) -> &mut Self {
        self.stdout(format!("<green><tick></> {}", message))
    }

    /// Prints to stdout and adds some warning flare to text
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    /// logger.warn("This is a warning");
    /// ```
    ///
    /// Equivalent macro: `warn!()`
    pub fn warn<T: Display>(&mut self, message: T) -> &mut Self {
        self.stdout(format!("<yellow><warn></> {}", message))
    }

    /// Prints to stderr and adds some error flare to text
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    /// logger.error("Something broke, here's the error");
    /// ```
    ///
    /// Equivalent macro: `error!()`
    pub fn error<T: Display>(&mut self, message: T) -> &mut Self {
        self.stderr(format!("<red><cross></> {}", message))
    }

    /// Prints a specified amount of newlines to stdout
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    /// logger
    ///     .newline(5)
    ///     .info("Some newlines before info")
    ///     .newline(2)
    ///     .info("And some more in between");
    /// ```
    pub fn newline(&mut self, amount: usize) -> &mut Self {
        self.done();
        print!("{}", "\n".repeat(amount));
        self
    }

    /// Prints a specified amount of tabs to stdout
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    /// logger
    ///     .indent(1)
    ///     .warn("Indented warning eh? Stands out a bit")
    ///     .newline(5);
    /// ```
    pub fn indent(&mut self, amount: usize) -> &mut Self {
        self.done();
        print!("{}", "\t".repeat(amount));
        self
    }

    /// Starts a loading animation with the given message.
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// let mut logger = Logger::new();
    /// logger.loading("Counting to 52!");
    ///
    /// // counting happens here (somehow)
    ///
    /// logger
    ///     .done()
    ///     .success("Done counting, only took 1 million years");
    /// ```
    ///
    /// That's one way of doing it, but having to always call `.done()` doesn't
    /// look that tidy. Well you don't have to, unless you want. All other functions
    /// (success, info, error, etc.) call `.done()` just in case a loading thread is running
    /// already. A cleaner example would be:
    /// ```
    /// # use paris::Logger;
    /// let mut logger = Logger::new();
    /// logger.loading("Counting to 52! again");
    ///
    /// // ....
    ///
    /// logger.error("I give up, I can't do it again!");
    /// ```
    pub fn loading<T: Display>(&mut self, message: T) -> &mut Self {
        // If already running, stop the currently running thread
        // and clean it up before adding a new message.
        self.done();

        let mut status = self.is_loading.write().unwrap();
        *status = true;

        drop(status); // Release the lock so a mutable can be returned

        let status = self.is_loading.clone();
        let message = self.formatter.colorize(&message.to_string());

        self.loading_handle = Some(thread::spawn(move || {
            let frames: [&str; 6] = ["⠦", "⠇", "⠋", "⠙", "⠸", "⠴"];
            let mut i = 1;

            while *status.read().unwrap() {
                if i == frames.len() {
                    i = 0;
                }

                let message = format!("<cyan>{}</> {}", frames[i], &message);
                output::stdout(colorize_string(message), "", true);
                io::stdout().flush().unwrap();

                thread::sleep(Duration::from_millis(100));

                i += 1;
            }
        }));

        self
    }

    /// Stops the loading animation and clears the line so you can print something else
    /// when loading is done, maybe a success message. All other methods (success, warning, error, etc.)
    /// call this one automatically when called so you can use one of those directly
    /// for less clutter.
    pub fn done(&mut self) -> &mut Self {
        if !*self.is_loading.read().unwrap() {
            return self;
        }

        let mut status = self.is_loading.write().unwrap();
        *status = false;

        drop(status); // Release the lock so a mutable can be returned

        self.loading_handle
            .take()
            .expect("Called stop on a non-existing thread")
            .join()
            .expect("Could not join spawned thread");

        Ansi::clear_line();
        self
    }

    /// Forces the next statement to not output a newline
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    ///
    /// logger
    ///     .same().log("This is on one line")
    ///     .indent(4)
    ///     .log("This is on the same line!");
    /// ```
    pub fn same(&mut self) -> &mut Self {
        self.set_line_ending("");

        self
    }

    /// Add a custom key to the available list of keys
    ///
    /// # Example
    /// ```
    /// # use paris::Logger;
    /// # let mut logger = Logger::new();
    ///
    /// logger.add_style("lol", vec!["green", "bold", "on_blue"]);
    ///
    /// // '<lol>' can now be used as a key in strings and will contain
    /// // the defined colors and styles
    /// logger.info("<lol>much shorter than writing all of them</>");
    pub fn add_style(&mut self, key: &str, colors: Vec<&'a str>) -> &mut Self {
        self.formatter.new_style(key, colors);
        self
    }

    /// Output to stdout, add timestamps or on the same line
    fn stdout<T>(&mut self, message: T) -> &mut Self
    where
        T: Display,
    {
        self.done();
        let message = message.to_string();

        output::stdout(
            self.formatter.colorize(&message),
            &self.get_line_ending(),
            false,
        );
        self
    }

    /// Output to stderr, add timestamps or write on the same line
    fn stderr<T>(&mut self, message: T) -> &mut Self
    where
        T: Display,
    {
        self.done();
        let message = message.to_string();

        output::stderr(
            self.formatter.colorize(&message),
            &self.get_line_ending(),
            false,
        );
        self
    }

    /// Sets line ending to something specific
    /// mostly \n for now
    fn set_line_ending<T: Into<String>>(&mut self, ending: T) {
        self.line_ending = ending.into();
    }

    /// Return line ending based on whats already set
    /// set it back to newline if its not already
    fn get_line_ending(&mut self) -> String {
        let newline = String::from("\n");
        let empty = String::from("");

        if self.line_ending != newline {
            self.set_line_ending(newline);
            return empty;
        }

        newline
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{thread, time::Duration};

    #[test]
    fn loading() {
        let mut logger = Logger::new();
        logger.loading("Loading in the middle of a test is not good!");
        thread::sleep(Duration::from_secs(1));
        logger.done().success("Done loading!");

        logger.info("About to load again");
        logger
            .loading("Loading something else")
            .done()
            .error("Done loading instantly lol");
    }

    #[test]
    fn multiple_loading() {
        let mut logger = Logger::new();
        logger.loading("Loading in the middle of a test is not good!");
        thread::sleep(Duration::from_secs(1));
        logger.loading("This will break it?");
        thread::sleep(Duration::from_secs(1));

        logger.success("Loading done!");
    }

    #[cfg(feature = "timestamps")]
    #[test]
    fn loading_with_timestamps() {
        let mut logger = Logger::new();
        logger.loading("Loading in the middle of a test is not good!");
        thread::sleep(Duration::from_secs(4));
        logger.loading("Still loading...");
        thread::sleep(Duration::from_secs(4));

        logger.success("Loading done!");
    }

    #[test]
    fn same() {
        let mut logger = Logger::new();
        logger
            .same()
            .success("This is on one line")
            .indent(1)
            .info("This is on the same line!!!")
            .error("But this one isn't");

        logger.same();
        assert_eq!(logger.line_ending, String::from(""));

        logger.info("Reset the line");
        assert_eq!(logger.line_ending, String::from("\n"));
    }

    #[test]
    fn it_works() {
        let mut logger = Logger::new();

        logger
            .info("Somebody")
            .error("Once")
            .warn("Told")
            .success("Me")
            .newline(5)
            .log("A basic log eh")
            .indent(2)
            .info("If it didn't crash it's fine");
    }

    #[test]
    fn add_style_works() {
        let mut logger = Logger::new();

        logger.add_style("lmao", vec!["red", "on-green"]);
    }
}