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
use std::cmp::{max, Ordering};
use std::fmt::{Display, Formatter};

use crate::frequencies::errors::InvalidFrequency;
use crate::frequencies::validations::{
    validate_daily, validate_hourly, validate_minutely, validate_monthly, validate_secondly,
    validate_weekly, validate_yearly,
};
use crate::utils::{get_next_nth_weekday, weekday_ordinal, DateUtils};
use chrono::{DateTime, Datelike, Duration, Month, Timelike, Utc, Weekday};
use std::ops::{Add, Sub};
use std::str::FromStr;

/// Representation of the frequency of a recurrence.
/// E.g. Once a day, Twice a week, etc.
///
/// Examples:
/// ```
/// use rrules::{Frequency};
///
/// let once_a_day = Frequency::Daily {interval: 1, by_time: vec![]};
/// assert_eq!(once_a_day.to_string(), "Once a day");
///
/// let three_times_a_month = Frequency::Monthly {
///     interval: 1,
///     by_month_day: vec![1, 10, 20],
///     nth_weekdays: vec![]
/// };
/// assert_eq!(three_times_a_month.to_string(), "3 times a month");
/// ```
pub enum Frequency {
    Secondly {
        interval: i32,
    },
    Minutely {
        interval: i32,
    },
    Hourly {
        interval: i32,
    },
    Daily {
        interval: i32,
        by_time: Vec<Time>,
    },
    Weekly {
        interval: i32,
        by_day: Vec<Weekday>,
    },
    Monthly {
        interval: i32,
        by_month_day: Vec<i32>,
        nth_weekdays: Vec<NthWeekday>,
    },
    Yearly {
        interval: i32,
        by_monthly_date: Vec<MonthlyDate>,
    },
}

/// Representation of the nth day of the week
/// E.g. 2nd Monday, 3rd Tuesday, etc.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct NthWeekday {
    pub week_number: i32,
    pub weekday: Weekday,
}

impl NthWeekday {
    pub fn new(weekday: Weekday, week_number: i32) -> NthWeekday {
        NthWeekday {
            week_number,
            weekday,
        }
    }
}

impl PartialOrd<Self> for NthWeekday {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for NthWeekday {
    fn cmp(&self, other: &Self) -> Ordering {
        let week_number_cmp = self.week_number.cmp(&other.week_number);
        if week_number_cmp == Ordering::Equal {
            self.weekday
                .num_days_from_sunday()
                .cmp(&other.weekday.num_days_from_sunday())
        } else {
            week_number_cmp
        }
    }
}

/// Representation of a time containing hour:minute
/// E.g. 12:00, 23:59, etc.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct Time {
    pub hour: i32,
    pub minute: i32,
}

impl FromStr for Time {
    type Err = InvalidFrequency;

    fn from_str(time_str: &str) -> Result<Self, InvalidFrequency> {
        let mut parts = time_str.split(':');
        let hour = match parts.next() {
            None => {
                return Err(InvalidFrequency::Time {
                    message: format!("Invalid time: {time_str}"),
                })
            }
            Some(hour) => hour.parse::<i32>().unwrap(),
        };
        let minute = match parts.next() {
            None => {
                return Err(InvalidFrequency::Time {
                    message: format!("Invalid time: {time_str}"),
                })
            }
            Some(minute) => minute.parse::<i32>().unwrap(),
        };
        Ok(Time { hour, minute })
    }
}

/// Representation of a monthly date
/// E.g. 1st of January, 2nd of February, etc.
pub struct MonthlyDate {
    pub month: Month,
    pub day: i32,
}

impl Frequency {
    /// Verifies if the frequency is valid.
    pub fn is_valid(&self) -> Result<(), InvalidFrequency> {
        match self {
            Frequency::Secondly { interval } => validate_secondly(interval),
            Frequency::Minutely { interval } => validate_minutely(interval),
            Frequency::Hourly { interval } => validate_hourly(interval),
            Frequency::Daily { interval, by_time } => validate_daily(interval, by_time),
            Frequency::Weekly { interval, by_day } => validate_weekly(interval, by_day),
            Frequency::Monthly {
                interval,
                by_month_day,
                nth_weekdays,
            } => validate_monthly(interval, by_month_day, nth_weekdays),
            Frequency::Yearly {
                interval,
                by_monthly_date,
            } => validate_yearly(interval, by_monthly_date),
        }
    }

    /// Returns the next event date for the current frequencies config given the current date.
    /// Returns None if there is no next event.
    /// E.g. If the frequency is once a day and the current date is 2020-01-01, the next event date will be 2020-01-02.
    pub fn next_event(&self, current_date: &DateTime<Utc>) -> Option<DateTime<Utc>> {
        match self {
            Frequency::Secondly { interval } => {
                let next_date = current_date.add(chrono::Duration::seconds(*interval as i64));
                Some(next_date)
            }
            Frequency::Minutely { interval } => {
                let next_date = current_date.add(chrono::Duration::minutes(*interval as i64));
                Some(next_date)
            }
            Frequency::Hourly { interval } => {
                let next_date = current_date.add(chrono::Duration::hours(*interval as i64));
                Some(next_date)
            }
            Frequency::Daily { interval, by_time } => {
                next_daily_event(current_date, *interval, by_time)
            }
            Frequency::Weekly { interval, by_day } => {
                next_weekly_event(current_date, *interval, by_day)
            }
            Frequency::Monthly {
                interval,
                by_month_day,
                nth_weekdays,
            } => _next_monthly_event(current_date, *interval, by_month_day, nth_weekdays),
            Frequency::Yearly {
                interval,
                by_monthly_date,
            } => next_yearly_event(current_date, *interval, by_monthly_date),
        }
    }

    /// Verifies if the specified date is a valid event date for the current frequency.
    /// E.g. If the frequency is once a day and the date is 2023-01-01, the method will return true.
    /// If the frequency is Once a week on Monday and the date is 2023-01-01, the method will return false
    /// because the date is not a Monday.
    ///
    /// ```
    /// use std::str::FromStr;
    /// use rrules::Frequency;
    /// use chrono::{Utc, DateTime, Duration, Weekday};
    ///
    /// let once_a_day = Frequency::Daily {interval: 1,by_time: vec![]};
    /// let sunday = DateTime::<Utc>::from_str("2023-01-01T00:00:00Z").unwrap();
    /// assert!(once_a_day.contains(&sunday));
    ///
    /// let every_monday = Frequency::Weekly {interval: 1, by_day: vec![Weekday::Mon]};
    /// assert!(!every_monday.contains(&sunday));
    /// ```
    pub fn contains(&self, date: &DateTime<Utc>) -> bool {
        match self {
            Frequency::Secondly { .. } => true,
            Frequency::Minutely { .. } => true,
            Frequency::Hourly { .. } => true,
            Frequency::Daily { by_time, .. } => {
                if by_time.is_empty() {
                    return true;
                }
                // Return 1 minute from current date to confirm if the current date could be
                // the next event date.
                let start = date.sub(Duration::minutes(1));
                match self.next_event(&start) {
                    None => false,
                    Some(next_date) => next_date == *date,
                }
            }
            Frequency::Weekly { by_day, .. } => {
                by_day.is_empty() || by_day.contains(&date.weekday())
            }
            Frequency::Monthly {
                nth_weekdays,
                by_month_day,
                ..
            } => {
                if by_month_day.is_empty() && nth_weekdays.is_empty() {
                    return true;
                }
                let day = date.day() as i32;

                if !by_month_day.is_empty() {
                    return by_month_day.contains(&day);
                }
                let weekday = date.weekday();
                let week_number = weekday_ordinal(date);
                for nth in nth_weekdays {
                    if nth.weekday == weekday && nth.week_number == week_number {
                        return true;
                    }
                }
                false
            }
            Frequency::Yearly {
                by_monthly_date, ..
            } => {
                if by_monthly_date.is_empty() {
                    return true;
                }
                let month = date.month();
                let day = date.day() as i32;
                for monthly_date in by_monthly_date {
                    if monthly_date.month.number_from_month() == month && monthly_date.day == day {
                        return true;
                    }
                }
                false
            }
        }
    }
}

fn next_daily_event(
    current_date: &DateTime<Utc>,
    interval: i32,
    by_time: &Vec<Time>,
) -> Option<DateTime<Utc>> {
    let mut next_date = current_date.add(chrono::Duration::days(interval as i64));

    if !by_time.is_empty() {
        for time in by_time {
            let d = current_date
                .with_hour(time.hour as u32)
                .unwrap()
                .with_minute(time.minute as u32)
                .unwrap();
            if d > *current_date {
                return Some(d);
            }
        }

        // No hours left in the day, so we need to add a day
        next_date = next_date
            .with_hour(by_time[0].hour as u32)
            .unwrap()
            .with_minute(by_time[0].minute as u32)
            .unwrap();
    }
    Some(next_date)
}

fn next_weekly_event(
    current_date: &DateTime<Utc>,
    interval: i32,
    by_day: &Vec<Weekday>,
) -> Option<DateTime<Utc>> {
    let next_date = current_date.add(chrono::Duration::weeks(interval as i64));

    if !by_day.is_empty() {
        let current_weekday_num = current_date.weekday().num_days_from_sunday() + 1;
        let _d = current_date.format("%Y-%m-%d").to_string();
        for day in by_day {
            let day_num = day.num_days_from_sunday() + 1;
            if day_num > current_weekday_num {
                let diff = day_num - current_weekday_num;
                return Some(current_date.add(chrono::Duration::days(diff as i64)));
            }
        }
        // No days left in the week, so we need to add a week
        if let Some(d) = current_date.with_weekday(by_day[0]) {
            return d.shift_weeks(interval as i64);
        }
    }
    Some(next_date)
}

fn _next_monthly_event(
    current_date: &DateTime<Utc>,
    interval: i32,
    by_month_day: &Vec<i32>,
    nth_weekdays: &Vec<NthWeekday>,
) -> Option<DateTime<Utc>> {
    let next_date = current_date.shift_months(interval as i64);
    if !by_month_day.is_empty() {
        let current_month_day = current_date.day() as i32;
        for day in by_month_day {
            if *day > current_month_day {
                if let Some(d) = current_date.with_day(*day as u32) {
                    return Some(d);
                }
            }
        }
        // No days left in the month, so we need to add a month
        if let Some(d) = current_date.with_day(by_month_day[0] as u32) {
            return d.shift_months(interval as i64);
        }
    }
    if !nth_weekdays.is_empty() {
        return get_next_nth_weekday(current_date, interval as i64, nth_weekdays);
    }
    next_date
}

fn next_yearly_event(
    current_date: &DateTime<Utc>,
    interval: i32,
    by_monthly_date: &Vec<MonthlyDate>,
) -> Option<DateTime<Utc>> {
    if !by_monthly_date.is_empty() {
        for date in by_monthly_date {
            let month_number = date.month.number_from_month();
            let d = current_date
                .with_month(month_number)
                .unwrap()
                .with_day(date.day as u32);
            match d {
                Some(d) => {
                    if d > *current_date {
                        return Some(d);
                    }
                }
                None => return None,
            }
        }

        // No dates left in the year, so we need to add a year
        let month_number = by_monthly_date[0].month.number_from_month();
        let result = current_date
            .with_month(month_number)
            .unwrap()
            .with_day(by_monthly_date[0].day as u32);
        return match result {
            Some(d) => d.shift_years(interval as i64),
            None => None,
        };
    }

    current_date.shift_years(interval as i64)
}

impl Display for Frequency {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Frequency::Secondly { interval } => {
                write!(f, "{}", get_interval_string(*interval, "second"))
            }
            Frequency::Minutely { interval } => {
                write!(f, "{}", get_interval_string(*interval, "minute"))
            }
            Frequency::Hourly { interval } => {
                write!(f, "{}", get_interval_string(*interval, "hour"))
            }
            Frequency::Daily { interval, by_time } => {
                let amount = match get_amount_format(by_time.len()) {
                    None => "".to_string(),
                    Some(v) => format!("{v} "),
                };
                let count = if *interval > 1 {
                    format!("every {interval}")
                } else {
                    "a".to_string()
                };
                let plural = if *interval > 1 { "s" } else { "" };
                write!(f, "{amount}{count} day{plural}")
            }
            Frequency::Weekly { interval, by_day } => {
                let amount = match get_amount_format(by_day.len()) {
                    None => "".to_string(),
                    Some(v) => format!("{v} "),
                };
                let count = if *interval > 1 {
                    format!("every {interval}")
                } else {
                    "a".to_string()
                };
                let plural = if *interval > 1 { "s" } else { "" };
                write!(f, "{amount}{count} week{plural}")
            }
            Frequency::Monthly {
                interval,
                by_month_day,
                nth_weekdays,
            } => {
                let amount = match get_amount_format(max(by_month_day.len(), nth_weekdays.len())) {
                    None => "".to_string(),
                    Some(v) => format!("{v} "),
                };
                let count = if *interval > 1 {
                    format!("every {interval}")
                } else {
                    "a".to_string()
                };
                let plural = if *interval > 1 { "s" } else { "" };
                write!(f, "{amount}{count} month{plural}")
            }
            Frequency::Yearly {
                interval,
                by_monthly_date,
            } => {
                let amount = match get_amount_format(by_monthly_date.len()) {
                    None => "".to_string(),
                    Some(v) => format!("{v} "),
                };
                let count = if *interval > 1 {
                    format!("every {interval}")
                } else {
                    "a".to_string()
                };
                let plural = if *interval > 1 { "s" } else { "" };
                write!(f, "{amount}{count} year{plural}")
            }
        }
    }
}

fn get_interval_string(interval: i32, unit: &str) -> String {
    let count = if interval > 1 {
        format!("Every {interval}")
    } else {
        "Every".to_string()
    };
    let plural = if interval > 1 { "s" } else { "" };
    format!("{count} {unit}{plural}")
}

fn get_amount_format(by_time: usize) -> Option<String> {
    match by_time {
        0 | 1 => Some("Once".to_string()),
        2 => Some("Twice".to_string()),
        amount => Some(format!("{amount} times")),
    }
}