Skip to main content

whichtime_sys/parsers/nl/
weekday.rs

1//! Dutch weekday parser
2//!
3//! Handles Dutch weekday expressions like:
4//! - "maandag", "op dinsdag"
5//! - "volgende vrijdag", "afgelopen vrijdag"
6//! - "vrijdag volgende week"
7
8use crate::components::Component;
9use crate::context::ParsingContext;
10use crate::dictionaries::RelativeModifier;
11use crate::dictionaries::nl::{get_relative_modifier, get_weekday};
12use crate::error::Result;
13use crate::parsers::Parser;
14use crate::results::ParsedResult;
15use chrono::{Datelike, Duration};
16use fancy_regex::Regex;
17use std::sync::LazyLock;
18
19static PATTERN: LazyLock<Regex> = LazyLock::new(|| {
20    Regex::new(
21        r"(?ix)
22        (?<![a-zA-Z])
23        (?:(?:op|om|tijdens)\s+)?
24        (?:
25            (?P<prefix>deze|dit|volgende|volgend|komende|komend|afgelopen|vorige|vorig|laatste)
26            \s+
27        )?
28        (?P<weekday>zondag|zon|zo|maandag|maan|ma|dinsdag|dins|di|woensdag|woens|wo|donderdag|donder|do|vrijdag|vrij|vr|zaterdag|zater|za)
29        (?:
30            \s+
31            (?P<suffix_mod>volgende|volgend|komende|komend|afgelopen|vorige|vorig)
32            \s+week
33        )?
34        (?=\W|$)
35        "
36    ).unwrap()
37});
38
39/// Dutch weekday parser
40pub struct NLWeekdayParser;
41
42impl NLWeekdayParser {
43    pub fn new() -> Self {
44        Self
45    }
46}
47
48impl Default for NLWeekdayParser {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl Parser for NLWeekdayParser {
55    fn name(&self) -> &'static str {
56        "NLWeekdayParser"
57    }
58
59    fn should_apply(&self, _context: &ParsingContext) -> bool {
60        true
61    }
62
63    fn parse(&self, context: &ParsingContext) -> Result<Vec<ParsedResult>> {
64        let mut results = Vec::new();
65        let ref_date = context.reference.instant;
66        let ref_weekday = ref_date.weekday().num_days_from_sunday() as i64;
67
68        let mut start = 0;
69        while start < context.text.len() {
70            let search_text = &context.text[start..];
71            let captures = match PATTERN.captures(search_text) {
72                Ok(Some(caps)) => caps,
73                Ok(None) => break,
74                Err(_) => break,
75            };
76
77            let full_match = match captures.get(0) {
78                Some(m) => m,
79                None => break,
80            };
81
82            let match_start = start + full_match.start();
83            let match_end = start + full_match.end();
84            let matched_text = full_match.as_str();
85
86            let weekday_str = captures
87                .name("weekday")
88                .map(|m| m.as_str().to_lowercase())
89                .unwrap_or_default();
90            let prefix_str = captures.name("prefix").map(|m| m.as_str().to_lowercase());
91            let suffix_mod_str = captures
92                .name("suffix_mod")
93                .map(|m| m.as_str().to_lowercase());
94
95            let Some(weekday) = get_weekday(&weekday_str) else {
96                start = match_end;
97                continue;
98            };
99
100            let target_weekday = weekday as i64;
101
102            // Determine modifier from prefix or suffix
103            let modifier = prefix_str
104                .as_ref()
105                .and_then(|s| get_relative_modifier(s))
106                .or_else(|| {
107                    suffix_mod_str
108                        .as_ref()
109                        .and_then(|s| get_relative_modifier(s))
110                });
111
112            // Calculate days offset
113            let days_offset = match modifier {
114                Some(RelativeModifier::Next) => {
115                    let diff = target_weekday - ref_weekday;
116                    if diff <= 0 { diff + 7 } else { diff }
117                }
118                Some(RelativeModifier::Last) => {
119                    let diff = target_weekday - ref_weekday;
120                    if diff >= 0 { diff - 7 } else { diff }
121                }
122                Some(RelativeModifier::This) | None => {
123                    // Default behavior: find closest day
124                    // "This Friday" usually means coming Friday, or past Friday if recent?
125                    // whichtime-sys conventions usually prefer forward or closest.
126                    // Let's follow `de` parser logic: closest within -3 to +3 range or similar.
127
128                    let diff = target_weekday - ref_weekday;
129                    if diff == 0 {
130                        0
131                    } else if diff > 0 {
132                        if diff <= 3 { diff } else { diff - 7 }
133                    } else if diff >= -3 {
134                        diff
135                    } else {
136                        diff + 7
137                    }
138                }
139            };
140
141            // Special handling for "vrijdag volgende week" (Next week's Friday)
142            // If suffix "volgende week" is present, it implies +1 week relative to *this* week's Friday?
143            // "vrijdag volgende week" -> Friday of the next week.
144            // If today is Monday, "next Friday" usually means Friday of THIS week (if close) or NEXT week.
145            // BUT "vrijdag volgende week" explicitly shifts the week.
146            // So we find "Friday" of the current week, then add 7 days?
147            // Or find "Next Friday" then add 7 days?
148
149            // Interpretation: "vrijdag volgende week"
150            // 1. Find Friday of this week.
151            // 2. Add 7 days.
152
153            let final_offset = if suffix_mod_str.is_some() {
154                if modifier == Some(RelativeModifier::Next) {
155                    // "vrijdag volgende week"
156                    // Find "this week's Friday" (forward or backward)?
157                    // Usually relative to start of week or just +7 days from "this Friday".
158                    // Let's say: target is Friday of (Current Week + 1).
159                    // Current week defined by reference date.
160                    // Simple approach: Calculate days to next Friday, then ensure it's in next week.
161
162                    // Alternative: (target_weekday - ref_weekday + 7) % 7 + (days until next week)
163                    // Actually, let's use the logic: "Friday of next week".
164                    // Calculate Friday of current week, add 7.
165                    // Current week's Friday relative to today:
166                    // ref_weekday is today's index (0=Sun).
167                    // target_weekday is Friday (5).
168                    // Friday of THIS week: target_weekday - ref_weekday.
169                    // Example: Today=Wed(3), Fri(5). Diff=2. Date+2 is Friday. Next week Fri is Date+9.
170                    // Example: Today=Sat(6), Fri(5). Diff=-1. Date-1 is Friday. Next week Fri is Date+6.
171                    // Wait, "next week" usually starts on Monday or Sunday.
172                    // "vrijdag volgende week" means the Friday that falls in the week after the current week.
173                    // If today is Monday, "next week" starts next Monday. Friday next week is > 7 days away.
174
175                    let diff = target_weekday - ref_weekday;
176
177                    // Let's stick to `de` logic:
178                    if diff > 0 {
179                        diff + 7 // If Friday is later this week, add 7 to get to next week
180                    } else {
181                        // If Friday was earlier this week, add 7 to get to next week? No.
182                        // If Today is Fri, "Friday next week" is +7.
183                        // If Today is Sat, "Friday next week" is +6? No, that's "next Friday".
184                        // "Friday next week" means Friday of the NEXT week.
185                        // If Today is Sat(6), Friday(5) of THIS week was yesterday (-1).
186                        // Friday of NEXT week is -1 + 7 = +6. (Which is the coming Friday).
187                        // Is "Next Friday" same as "Friday next week"?
188                        // Often "Next Friday" means the immediate next one.
189                        // "Friday next week" is explicit.
190
191                        // Let's assume: (target - ref) + 7, but adjusted so we land in next week.
192                        // Simpler: Find the Friday that is in the week starting after this week.
193
194                        diff + 7
195                    }
196                } else if modifier == Some(RelativeModifier::Last) {
197                    // "vrijdag vorige week"
198                    let diff = target_weekday - ref_weekday;
199                    diff - 7
200                } else {
201                    days_offset
202                }
203            } else {
204                days_offset
205            };
206
207            let target_date = ref_date + Duration::days(final_offset);
208
209            let mut components = context.create_components();
210            components.assign(Component::Year, target_date.year());
211            components.assign(Component::Month, target_date.month() as i32);
212            components.assign(Component::Day, target_date.day() as i32);
213            components.assign(Component::Weekday, target_weekday as i32);
214
215            // Find actual text bounds (trim leading/trailing non-alphanumeric)
216            let actual_start = matched_text
217                .find(|c: char| c.is_alphanumeric())
218                .unwrap_or(0);
219            let actual_end = matched_text
220                .rfind(|c: char| c.is_alphanumeric())
221                .map(|i| i + matched_text[i..].chars().next().map_or(1, char::len_utf8))
222                .unwrap_or(matched_text.len());
223
224            results.push(context.create_result(
225                match_start + actual_start,
226                match_start + actual_end,
227                components,
228                None,
229            ));
230
231            start = match_end;
232        }
233
234        Ok(results)
235    }
236}