elmo 0.0.1

Library for easy creation of persistent notifications
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
#![doc(html_logo_url = "https://i.imgur.com/Le9EOww.png")]
//! # Introduction
//!
//! This library provides functionality for emitting, scheduling and listing notifications. It utilizes
//! an SQLite database for storing regular events (notify at a given datetime) and recurring events
//! (notify at a given pattern). Basically, it is a combination of services that communicate with the
//! notification daemon of a UNIX system, play sounds via the sound output device of the system, and
//! insert/fetch events from the database.
//!
//! # Public functions
//!
//! Five public functions are available:
//! - **`set_event`** (Either insert a new entry in the database or emit a notification directly)
//! - **`emit_event`** (Sleep for a given duration in a separate thread or emit a notification directly)
//! - **`check_events`** (Check for entries within the database that should be emitted)
//! - **`list_events`** (List entries from the database)
//! - **`delete_event`** (Delete a recurring or regular event by ID)
//!
//! **`set_event`** requires an SQlitepool from the sqlx library and needs to be called from an
//! async function, while **`emit_event`** is the synchronous variation it doesn't require a
//! database connection. An event stored into the database by **`set_event`** can only be triggered
//! by calling **`check_events`**.
//!
//! The **`check_events`** function is designed to be used in combination with a cronjob or with a daemon,
//! as it simply checks if an entry within the database matches the current datetime (or in case of
//! recurring events, if we missed it within a range of 30 minutes).
//!
//! The **`list_events`** function is
//! utilized to pretty-print events to the terminal, with a fixed format, so its use case is quite
//! specialized at the moment. In order to create a notification, you have to first establish a
//! connection to an SQLite database pool and fill out an `EventTemplate`.
//!
//! ## Example with a database
//!
//! Here we create an in-memory SQLite database with the events table and insert a single event,
//! this is not a very practical example as events stored in an in-memory database are lost when
//! the main function exits, but it shows how the function should be used.
//!
//! The function `check_events` can be used to display notifications, that are stored in a
//! database.
//!
//! ```edition2018
//! use eyre::Result;
//! use elmo_lib::{set_event, EventTemplate};
//! use sqlx::sqlite::SqlitePool;
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     let pool = SqlitePool::connect("file::memory:").await?;
//!     sqlx::query(
//!         "CREATE TABLE IF NOT EXISTS events(
//!             id INTEGER PRIMARY KEY NOT NULL,
//!             name TEXT NOT NULL,
//!             description TEXT NULL,
//!             event_date TEXT NOT NULL,
//!             icon TEXT NULL,
//!             sound_file_path TEXT NULL
//!             )
//!         "
//!         ).execute(&pool).await?;
//!
//!     let new_event = EventTemplate {
//!         name: String::from("Test notification"),
//!         desc: String::from("description of an event in the future"),
//!         date_str: Some(String::from("2099-10-10T18:00")),
//!         wait_expr: None,
//!         cron_str: None,
//!         icon_name: Some(String::from("future_icon")),
//!         sound_path: None,
//!         announce: true,
//!         test_sound: false,
//!     };
//!     set_event(new_event, &pool).await?;
//!     Ok(())
//! }
//! ```
//!
//! Within the repository of this project you can locate the `migrations/1_events.sql` file, which
//! contains the SQL statements for the two tables used by the project.
//!
//! To create a new SQLite database and create the required tables issue the following command:
//! ```bash
//! sqlite3 /tmp/events.db < /path/to/elmo/migrations/1_events.sql
//! ```
//!
//! ## Example without a database
//!
//! This example doesn't utilize a database but instead creates a separate thread that sleeps for
//! the specified amount of time.
//!
//! ```edition2018
//! use elmo_lib::{emit_event, EventTemplate};
//!
//! fn main() {
//!     let new_event = EventTemplate {
//!         name: String::from("Test notification"),
//!         desc: String::from("description of a notification in 5 minutes"),
//!         date_str: None,
//!         wait_expr: Some(String::from("5 seconds")),
//!         cron_str: None,
//!         icon_name: Some(String::from("dog_icon")),
//!         sound_path: None,
//!         announce: true,
//!         test_sound: false,
//!     };
//!     emit_event(new_event);
//! }
//! ```
//!
//! # Additional hints
//!
//! To use custom icons you have to place the new images into a folder that is known to the
//! notification daemon.  Please refer to the documnetation of the software you use on your system to
//! find out how to declare custom locations, for example in [dunst](https://dunst-project.org/) you
//! simply have to add the folder to the `icon_path` variable in the configuration (dunstrc).
mod events;

use crate::events::{CronEvent, CronEventRequest, Event, EventRepo, EventRequest};
use chrono::offset::TimeZone;
use chrono::{DateTime, Local, NaiveDateTime};
use cron::Schedule;
use eyre::{eyre, Result, WrapErr};
use notify_rust::Notification;
use rodio::{Decoder, OutputStream, Sink};
pub use sqlx::sqlite::SqlitePool;

use std::fs::File;
use std::io::BufReader;
use std::str::FromStr;
use std::thread;

static SQLITE_DATE: &str = "%Y-%m-%d %H:%M:%S";
static CLI_DATE: &str = "%Y-%m-%dT%H:%M";

/// TODO Implement an optional maximum sound playing time as a parameter
/// Fetch the sound device of the system, decode the sound file and play the sound.
///
/// # Parameters
/// - `sound_file_str`L Path on the system to sound file to be played
fn play_sound(sound_file_str: &str) -> Result<()> {
    let stream = OutputStream::try_default().wrap_err("Unable to open sound output stream")?;
    let (_stream, stream_handle) = stream;
    let sink = Sink::try_new(&stream_handle).wrap_err("Unable to open sound output device")?;
    let file_buffer: BufReader<File> = BufReader::new(File::open(sound_file_str)?);
    match Decoder::new(file_buffer) {
        Ok(x) => sink.append(x),
        Err(why) => return Err(eyre!(why)),
    }
    sink.sleep_until_end();
    Ok(())
}

/// Emit a notification and play a sound if available.
///
/// # Parameters:
/// - `name`: Title of the notification window
/// - `desc`: Text body of the notification window
/// - `icon`: Optional name without extension or path of the icon for the notification
/// - `sound_file_path`: Optional full-path to the sound file (e.g. mp3, mpg, wav etc)
fn notify(
    name: String,
    desc: String,
    icon: Option<String>,
    sound_file_path: Option<String>,
) -> Result<()> {
    let icon_name = match icon {
        Some(icon) => icon,
        None => "".to_string(),
    };
    // TODO make the persistence of the notification configurable
    Notification::new()
        .summary(&name)
        .body(&desc)
        .icon(&icon_name)
        .timeout(0)
        .show()
        .unwrap();

    if sound_file_path.is_some() {
        play_sound(&sound_file_path.unwrap())?;
    }
    Ok(())
}

/// Describe how much time has passed since the notification should have been triggered.
///
/// # Parameters
///
/// - `desc`: The current notification body
/// - `diff_in_sec`: The difference between the trigger date of the event and now
fn prepare_notification_body(
    event_desc: Option<String>,
    now: NaiveDateTime,
    event_date: NaiveDateTime,
) -> String {
    let diff_in_sec = now.signed_duration_since(event_date).num_seconds();
    let mut description = match event_desc {
        Some(x) => x,
        None => "".to_string(),
    };
    if diff_in_sec > 60 {
        // Notify how much time has passed since the scheduled date
        // This useful when the system has been shutdown during the
        // scheduled event
        let time_passed = match diff_in_sec {
            i if i > 120 && i <= 7200 => format!("{} minutes ago", i / 60),
            i if i > 7200 && i <= 172800 => format!("{} hours ago", i / 3600),
            i if i > 172800 && i <= 1209600 => format!("{} days ago", i / 86400),
            i if i > 1209600 => format!("{} weeks ago", i / 604800),
            _ => format!("{} seconds ago", diff_in_sec),
        };
        if description.is_empty() {
            description.push_str(&time_passed);
        } else {
            description.push_str(format!("\n{}", time_passed).as_ref());
        }
    }
    description
}

/// Get all scheduled events matching the cron expression between the
/// start and end date, that occur after the last notification was triggered.
///
/// # Parameters
///
/// - `start_date`: Datetime in the past used to find events that were missed
///                 because the system was powered down
/// - `end_date`: Upper end of the date range to look for valid events
/// - `last_notify_date`: Datetime stored in the database when the event was triggered,
///                       used to avoid triggering multiple times in a row, when the
///                       time between each check is lower than the than the time
///                       between each trigger of this event
/// - `cron_string`: Cron expression of the event to find scheduled dates
///
/// # Returns
///
/// - `valid_events`: All scheduled dates that satisfy the conditions
fn get_valid_scheduled_dates(
    start_date: DateTime<Local>,
    end_date: NaiveDateTime,
    last_notify_date: Option<String>,
    cron_string: String,
) -> Result<Vec<NaiveDateTime>> {
    let schedule = Schedule::from_str(&cron_string)?;
    // Search for all matching events within (now - 5min) and now
    // pick the last one for the notification
    let valid_events = schedule
        .after(&start_date)
        .take(5)
        .filter(|x| x <= &Local.from_local_datetime(&end_date).unwrap())
        .map(|x| x.naive_local());
    let last_notify_date = match last_notify_date {
        Some(date) => Some(NaiveDateTime::parse_from_str(&date, SQLITE_DATE)?),
        None => None,
    };
    let valid_events: Vec<NaiveDateTime> = match last_notify_date {
        Some(date) => valid_events.filter(|x| x > &date).collect(),
        None => valid_events.collect(),
    };
    Ok(valid_events)
}

/// Search for upcoming or just missed events within all database tables.
///
/// The events table is scanned for events that either match the current date or which could not be
/// notified as the no check was executed at the scheduled datetime, the event is notified and
/// deleted from the database.
/// The recurring_events table is scanned for the most recent match to the cronjob pattern within
/// the last 30 minutes, the last notification date is updated to avoid issuing the same
/// notification multiple times.
///
/// # Parameters
///
/// - `pool`: instance of an SQLite database pool, that takes SQL requests
pub async fn check_events(pool: &SqlitePool) -> Result<()> {
    let now: NaiveDateTime = Local::now().naive_local();
    let past_events = Event::find_current_events(pool, now.to_string()).await?;
    // FIXME current problem is that if multiple events are handled at the
    // same time and each of them emits a sound, then the sound device is blocked
    // by each event
    for event in past_events {
        let event_date: NaiveDateTime =
            NaiveDateTime::parse_from_str(&event.date, SQLITE_DATE).unwrap();
        let description: String = prepare_notification_body(event.description, now, event_date);

        notify(
            event.name,
            description,
            event.icon_name,
            event.sound_file_path,
        )?;
        Event::delete_event(pool, event.id).await?;
    }

    let recurring_events = CronEvent::find_events(pool).await?;
    let past_events_check = Local
        .from_local_datetime(
            &now.checked_sub_signed(chrono::Duration::minutes(30))
                .unwrap(),
        )
        .unwrap();

    for event in recurring_events {
        let valid_dates = get_valid_scheduled_dates(
            past_events_check,
            now,
            event.last_notification,
            event.cron_string,
        )?;

        if valid_dates.is_empty() {
            continue;
        }
        let event_date: NaiveDateTime = *valid_dates.last().unwrap();
        let description = prepare_notification_body(event.description, now, event_date);
        notify(
            event.name,
            description,
            event.icon_name,
            event.sound_file_path,
        )?;
        CronEvent::update_last_notification_date(pool, event.id, event_date).await?;
        // TODO Implement an optional maximum number of repetitions
    }
    Ok(())
}

/// Check if the user-supplied `date_str` from the EventTemplate is valid.
///
///A valid date must be in the future and must have the following format: "YYYY-mm-ddTHH:MM"
///
///# Parameter
///
///- `date_str`: User-supplied string from the EventTemplate
///
///# Returns
///
///- `date`: Datetime without timezone information as String
fn parse_date(date_str: &str) -> Result<String> {
    let now: NaiveDateTime = Local::now().naive_local();
    let date = NaiveDateTime::parse_from_str(date_str, CLI_DATE)?;
    if date < now {
        return Err(eyre!("Date must be in the future, got: {}", date));
    }
    Ok(date.to_string())
}

/// Interpret a time duration string expression and add it onto the current date.
///
/// # Parameters
///
/// - `expr`: String from the argument parser containing a time duration expression.
///           Examples: 1 second, 4 minutes, 3 hours, 2 weeks 4 days 3 hours
/// - `now`: The current date and time without timezone information
///
/// # Returns:
///
/// - A new NaiveDateTime which is equal to `now` + `expr`
fn get_date_after_duration(expr: &str, now: NaiveDateTime) -> Result<String> {
    let duration = parse_duration::parse(expr);
    if duration.is_err() {
        // Get the relevant part of the error message without the Error name
        // We could also do this with .description() but that is deprecated
        return Err(eyre!(format!(
            "Invalid duration expression because {}",
            duration
                .as_ref()
                .err()
                .unwrap()
                .to_string()
                .split(": ")
                .last()
                .unwrap()
        )));
    }
    let chrono_duration = chrono::Duration::from_std(duration.unwrap())?;
    Ok(now
        .checked_add_signed(chrono_duration)
        .ok_or_else(|| eyre!("Invalid duration {}", chrono_duration))?
        .format("%Y-%m-%d %H:%M:%S")
        .to_string())
}

/// Structure describing a notification
#[derive(Clone)]
pub struct EventTemplate {
    /// Title of the notification
    pub name: String,

    /// Body of the notification message
    pub desc: String,

    /// Optional specific datetime in the future with the format YYYY-mm-ddTHH:MM
    ///
    /// # Example
    /// - `2023-10-03T15:00`
    pub date_str: Option<String>,

    /// Optional duration expression that states a time span from now to now + duration as the
    /// waiting time until the notification is issued.
    ///
    /// # Example
    /// - `5 min`
    /// - `30 minutes`
    /// - `20 seconds`
    /// - `3 days`
    pub wait_expr: Option<String>,

    /// An optional cron pattern to store in the database for recurring events.
    ///
    /// # Example
    /// - `* */5 * * * *` (Every 5 minutes)
    /// - `* 30 16 * * *` (Every day at 16:30)
    pub cron_str: Option<String>,

    /// Optional filename without extension or path of a specific icon, the icon must be placed within a
    /// folder that is known to the notification daemon.
    pub icon_name: Option<String>,

    /// Optional full-path to sound file (.mp3, .mpg, etc.)
    pub sound_path: Option<String>,

    /// Decide whether to announce the notification in advance when either `date_str`, `wait_expr`,
    /// or `cron_str` are given, the announcement shows the content of the notification and might be
    /// used to test if the EventTemplate works as expected.
    /// When `test_sound` is true and the `sound_path` points to a valid file the sound is played
    /// during the announcement.
    pub announce: bool,

    /// Only works in combination with `announce` and `sound_path`, play the sound file during the
    /// announcement to check in advance if it works.
    pub test_sound: bool,
}

/// Handle adding a new event to the database and announce the creation.
///
/// # Parameters
///
/// - `template`: Structure that defines a new event
/// - `pool`: Instance of an SQLite database pool, that takes SQL requests
async fn schedule_event(template: EventTemplate, pool: &SqlitePool) -> Result<()> {
    let mut notify_at = String::from("");
    let mut date: String = String::from("");
    // TODO Make sure that only valid dates are entered into the database
    if let Some(ref date_str) = &template.date_str {
        date = parse_date(date_str)?;
    } else if let Some(ref expr) = &template.wait_expr {
        let now: NaiveDateTime = Local::now().naive_local();
        date = get_date_after_duration(expr, now)?;
    } else if let Some(ref cron_expr) = &template.cron_str {
        // Verify that the cron expression is valid
        // TODO only take the last 5 elements from the expected 6 elements from the
        // user as the first element describes seconds which is meaningless if we check
        // with crontab
        Schedule::from_str(cron_expr)?;
        // TODO implement parse to human readable cron
        notify_at = format!("trigger at {}", cron_expr);
        let request = CronEventRequest {
            name: template.name.to_string(),
            description: template.desc.to_string(),
            cron_string: cron_expr.to_string(),
            icon_name: template.icon_name.as_ref().map(|x| x.to_string()),
            sound_file_path: template.sound_path.as_ref().map(|x| x.to_string()),
        };
        CronEvent::create_event(pool, request).await?;
    }
    if !date.is_empty() {
        notify_at = date.clone();
        let request = EventRequest {
            name: template.name.to_string(),
            description: template.desc.to_string(),
            date,
            icon_name: template.icon_name.as_ref().map(|x| x.to_string()),
            sound_file_path: template.sound_path.as_ref().map(|x| x.to_string()),
        };
        Event::create_event(pool, request).await?;
    }

    if template.announce {
        let mut with_sound = String::from("");
        if template.test_sound {
            with_sound = String::from("\n(play the sound as a test..)")
        }
        let display_name = String::from("New notification created");
        let display_desc = format!(
            "Title:\n{}\n\nDescription:\n{}\n\nNotify at:\n{}\n{}",
            template.name, template.desc, notify_at, with_sound
        );
        notify(
            display_name,
            display_desc,
            template.icon_name.to_owned(),
            match template.test_sound {
                true => template.sound_path.to_owned(),
                false => None,
            },
        )?;
    }
    Ok(())
}

/// Create a delayed, recurring or direct notification.
///
/// # Parameters
///
/// - `template`: Structure that defines a new event
/// - `pool`: Optional instance of a Sqlite database pool
///
/// # Errors
///
/// Possible errors are:
/// - an invalid connection to the database
/// - unable to access the sound output device
/// - An invalid input date, which is either not in the format of
///   YYYY-mm-ddTHH:MM or smaller than now
/// - An invalid duration value for the `--wait` argument
/// - An incorrect cron string
pub async fn set_event(template: EventTemplate, pool: &SqlitePool) -> Result<()> {
    if template.date_str.is_some() || template.cron_str.is_some() || template.wait_expr.is_some() {
        schedule_event(template, pool).await?;
    } else {
        notify(
            template.name.to_owned(),
            template.desc.to_owned(),
            template.icon_name.to_owned(),
            template.sound_path.to_owned(),
        )?;
    }
    Ok(())
}

pub fn emit_event(template: EventTemplate) -> Result<()> {
    let local_dates: Vec<NaiveDateTime>;
    if let Some(ref date_str) = template.date_str {
        let date = parse_date(&date_str.to_string())?;
        local_dates = vec![NaiveDateTime::parse_from_str(&date, SQLITE_DATE)
            .wrap_err(format!("Invalid date {}", date))?]
    } else if let Some(ref expr) = template.wait_expr {
        let now: NaiveDateTime = Local::now().naive_local();
        let date = get_date_after_duration(expr.as_ref(), now)?;
        local_dates = vec![NaiveDateTime::parse_from_str(&date, SQLITE_DATE)
            .wrap_err(format!("Invalid date {}", date))?]
    } else if let Some(ref cron_expr) = template.cron_str {
        // TODO make the amount of dates configurable
        local_dates = Schedule::from_str(cron_expr.as_ref())?
            .upcoming(Local)
            .take(50)
            .map(|date| date.naive_local())
            .collect();
    } else {
        notify(
            template.name.to_string(),
            template.desc.to_string(),
            template.icon_name,
            template.sound_path,
        )?;
        return Ok(());
    }
    let dates = local_dates;
    // let name = template.name.to_string();
    // let desc = template.desc.to_string();
    // let icon = template.icon_name.map(|x| x.to_string());
    // let sound = template.sound_path.map(|x| x.to_string());
    std::thread::spawn(move || {
        for date in dates {
            let now: NaiveDateTime = Local::now().naive_local();
            let duration = date.signed_duration_since(now);
            thread::sleep(duration.to_std().unwrap());
            let notify_result = notify(
                template.name.to_string(),
                template.desc.to_string(),
                template.icon_name.as_ref().map(|x| x.to_string()),
                template.sound_path.as_ref().map(|x| x.to_string()),
            );
            assert!(
                !notify_result.is_err(),
                "Notification failed {}",
                notify_result.err().unwrap()
            );
        }
    });
    Ok(())
}

/// Colorful output to the terminal of all listed events
///
/// # Parameters:
///
/// - `response`: Either a vector of Event objects from the `events` table
///               or a vector or CronEvent objects from the 'recurring_events` table'.
///               Sorting of any kind has to be performed in advance.
/// - `print_function`: Specific function used to print the particular kind of object.
///                     Currently either `print_event` or `print_cron`.
fn print_event_response<T>(
    response: &[T],
    print_function: fn(&mut Box<term::StdoutTerminal>, event: &T),
) {
    let mut terminal = term::stdout().unwrap();
    for event in response {
        print_function(&mut terminal, event);
    }
}

fn print_header(id: i64, terminal: &mut Box<term::StdoutTerminal>) {
    terminal.fg(term::color::BRIGHT_YELLOW).unwrap();
    terminal.bg(term::color::BRIGHT_BLACK).unwrap();
    terminal.attr(term::Attr::Bold).unwrap();
    print!(" {0: <93}", format!("Event id: {}", id));
    terminal.reset().unwrap();
    println!();
}

fn print_title(title: &str, terminal: &mut Box<term::StdoutTerminal>) {
    terminal.fg(term::color::BRIGHT_YELLOW).unwrap();
    terminal.bg(term::color::BRIGHT_BLACK).unwrap();
    terminal.attr(term::Attr::Underline(true)).unwrap();
    print!(" {0: <27}", title);
    terminal.reset().unwrap();
}

fn print_content(content: &str, terminal: &mut Box<term::StdoutTerminal>) {
    terminal.fg(term::color::MAGENTA).unwrap();
    terminal.bg(term::color::BRIGHT_YELLOW).unwrap();
    terminal.attr(term::Attr::Bold).unwrap();
    print!(" {0: <65}", content);
    terminal.reset().unwrap();
    println!();
}

/// Colorful output to the terminal of a single event
///
/// # Parameters:
///
/// - `terminal`: Terminal writer with capabilities for changing colors and style
/// - `event`: A single row from the `events` database table
fn print_event(terminal: &mut Box<term::StdoutTerminal>, event: &Event) {
    print_header(event.id, terminal);
    print_title("Datetime", terminal);
    print_content(&event.date, terminal);
    print_title("Name", terminal);
    print_content(&event.name, terminal);
    print_title("Description", terminal);
    let desc = match &event.description {
        Some(x) => x,
        None => "---",
    };
    print_content(desc, terminal);
    print_title("Icon", terminal);
    let icon_name = match &event.icon_name {
        Some(x) => x,
        None => "---",
    };
    print_content(icon_name, terminal);
    print_title("Sound file", terminal);
    let sound_file_path = match &event.sound_file_path {
        Some(x) => x,
        None => "---",
    };
    print_content(sound_file_path, terminal);
    println!();
}

/// Parse the cron expression and get the next valid date that matches it
///
/// # Parameters
///
/// - `cron_string`: Cron expression with 6 fields (sec, min, hour, day(month), month, day(week))
///
/// # Result
///
/// - `upcoming`: The next matching date if any as DateTime without time zone information
fn get_upcoming_scheduled_date(cron_string: String) -> Result<NaiveDateTime> {
    let schedule = Schedule::from_str(&cron_string)?;
    let upcoming = schedule
        .upcoming(Local)
        .next()
        .ok_or_else(|| eyre!("No upcoming date found"))?
        .naive_local();
    Ok(upcoming)
}

// TODO write the events in order of their next notification
/// Colorful output to the terminal of a single recurring event
///
/// # Parameters:
///
/// - `terminal`: Terminal writer with capabilities for changing colors and style
/// - `event`: A single row from the `recurring_events` database table
fn print_cron(terminal: &mut Box<term::StdoutTerminal>, event: &CronEvent) {
    print_header(event.id, terminal);
    print_title("Next notification", terminal);
    let next_notify = get_upcoming_scheduled_date(event.cron_string.clone()).unwrap();
    print_content(&next_notify.to_string(), terminal);
    print_title("Last notification", terminal);
    let last_notify = match &event.last_notification {
        Some(date) => date.to_string(),
        None => "---".to_string(),
    };
    print_content(&last_notify, terminal);
    print_title("Name", terminal);
    print_content(&event.name, terminal);
    print_title("Description", terminal);
    let desc = match &event.description {
        Some(x) => x,
        None => "---",
    };
    print_content(desc, terminal);
    print_title("Cron expression", terminal);
    print_content(&event.cron_string, terminal);
    print_title("Icon", terminal);
    let icon_name = match &event.icon_name {
        Some(x) => x,
        None => "---",
    };
    print_content(icon_name, terminal);
    print_title("Sound file", terminal);
    let sound_file_path = match &event.sound_file_path {
        Some(x) => x,
        None => "---",
    };
    print_content(sound_file_path, terminal);
    println!();
}

/// List upcoming events or recurring events within the CLI with colorful output.
///
/// The colors are dependent on your bash color profile.
///
/// # Parameters
///
/// - `pool`: instance of an SQLite database pool, that takes SQL requests
/// - `expression`: Optional duration expression as String reference like `30 min` or `10 days`,
/// that limits the output to all events within now -> now + expression
/// - `cron_mode`: When set recurring events are listed instead of regular events from the events
/// table
pub async fn list_events(
    pool: &SqlitePool,
    expression: Option<&str>,
    cron_mode: bool,
) -> Result<()> {
    let now: NaiveDateTime = Local::now().naive_local();
    if let Some(expr) = expression {
        let end_date = get_date_after_duration(expr, now)?;
        print_event_response::<Event>(
            &Event::find_future_events(pool, now.to_string(), Some(end_date)).await?,
            print_event,
        );
    } else if cron_mode {
        print_event_response::<CronEvent>(&CronEvent::find_events(pool).await?, print_cron);
    } else {
        // TODO sort the events by their next notification date before printing them
        print_event_response::<Event>(
            &Event::find_future_events(pool, now.to_string(), None).await?,
            print_event,
        );
    }
    Ok(())
}

fn deletion_confirmation(event_id: i64, event_name: String) -> bool {
    loop {
        let mut input = String::new();
        println!(
            "Delete event {} with the name: {} (Y/n)",
            event_id, event_name
        );
        std::io::stdin()
            .read_line(&mut input)
            .expect("Unable to read user input");
        if !input.is_ascii() {
            println!("Input contains non ASCII values ...");
            continue;
        }
        match input.chars().next().unwrap().to_ascii_lowercase() {
            'y' | 'j' | '\n' => return true,
            'n' => return false,
            _ => continue,
        }
    }
}

/// Delete a recurring or regular event by ID.
///
/// # Parameters
/// - `pool`: instance of an SQLite database pool, that takes SQL requests
/// - `id`: ID of the event in the database
/// - `cron_mode`: Delete recurring events when this is `true`
/// - `confirm`: Ask the user for confirmation unless this is `true`
pub async fn delete_event(
    pool: &SqlitePool,
    id: i64,
    cron_mode: bool,
    confirm: bool,
) -> Result<()> {
    if !confirm {
        if cron_mode {
            let event = &CronEvent::get_event(pool, id).await;
            match event {
                Ok(ev) => {
                    if !deletion_confirmation(ev.id, ev.name.clone()) {
                        return Err(eyre!("Deletion aborted by the user"));
                    }
                }
                Err(err) => {
                    return Err(eyre!(
                        "Deletion of the recurring event with ID {} failed, due to {}",
                        id,
                        err
                    ))
                }
            }
        } else {
            let event = &Event::get_event(pool, id).await;
            match event {
                Ok(ev) => {
                    if !deletion_confirmation(ev.id, ev.name.clone()) {
                        return Err(eyre!("Deletion aborted by the user"));
                    }
                }
                Err(err) => {
                    return Err(eyre!(
                        "Deletion of the event with ID {} failed, due to {}",
                        id,
                        err
                    ))
                }
            }
        }
    }
    match cron_mode {
        true => &CronEvent::delete_event(pool, id).await?,
        false => &Event::delete_event(pool, id).await?,
    };
    Ok(())
}

pub async fn prepare_environment(pool: &SqlitePool) -> Result<()> {
    Event::create_table(pool).await?;
    CronEvent::create_table(pool).await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use chrono::NaiveDate;

    use super::*;

    #[test]
    fn test_get_valid_scheduled_dates_with_no_valid_dates() -> Result<(), String> {
        let start_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 0, 0);
        let end_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 5, 0);
        let last_notify_date = None;
        let cron_string = String::from("0 30 16 * * *");
        let expected_result = vec![];
        let result = get_valid_scheduled_dates(
            Local.from_local_datetime(&start_date).unwrap(),
            end_date,
            last_notify_date,
            cron_string,
        )
        .unwrap();
        assert_eq!(result, expected_result);
        Ok(())
    }

    #[test]
    fn test_get_valid_scheduled_dates_with_one_valid_date() -> Result<(), String> {
        let start_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 0, 0);
        let end_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 5, 0);
        let last_notify_date = None;
        let cron_string = String::from("0 3 16 * * *");
        let expected_result = vec![NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 3, 0)];
        let result = get_valid_scheduled_dates(
            Local.from_local_datetime(&start_date).unwrap(),
            end_date,
            last_notify_date,
            cron_string,
        )
        .unwrap();
        assert_eq!(result, expected_result);
        Ok(())
    }

    #[test]
    fn test_get_valid_scheduled_dates_with_multiple_matches() -> Result<(), String> {
        let start_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 0, 0);
        let end_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 10, 0);
        let last_notify_date = None;
        let cron_string = String::from("0 */3 * * * *");
        let expected_result = vec![
            NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 3, 0),
            NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 6, 0),
            NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 9, 0),
        ];
        let result = get_valid_scheduled_dates(
            Local.from_local_datetime(&start_date).unwrap(),
            end_date,
            last_notify_date,
            cron_string,
        )
        .unwrap();
        assert_eq!(result, expected_result);
        Ok(())
    }

    #[test]
    fn test_get_valid_scheduled_dates_with_last_notify_hide_past_events() -> Result<(), String> {
        let start_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 0, 0);
        let end_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 10, 0);
        let last_notify_date = Some(String::from("2021-09-10 16:05:00"));
        let cron_string = String::from("0 */5 * * * *");
        let expected_result = vec![NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 10, 0)];
        let result = get_valid_scheduled_dates(
            Local.from_local_datetime(&start_date).unwrap(),
            end_date,
            last_notify_date,
            cron_string,
        )
        .unwrap();
        assert_eq!(result, expected_result);
        Ok(())
    }

    #[test]
    fn test_get_valid_scheduled_dates_with_last_notify_no_matches() -> Result<(), String> {
        let start_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 0, 0);
        let end_date = NaiveDate::from_ymd(2021, 9, 10).and_hms(16, 15, 0);
        let last_notify_date = Some(String::from("2021-09-10 16:00:00"));
        let cron_string = String::from("0 */30 * * * *");
        let expected_result = vec![];
        let result = get_valid_scheduled_dates(
            Local.from_local_datetime(&start_date).unwrap(),
            end_date,
            last_notify_date,
            cron_string,
        )
        .unwrap();
        assert_eq!(result, expected_result);
        Ok(())
    }
}