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
//! Module related to parsing the date units
//! Create a `ParsedDatetime` from units

use crate::{calendars::Calendar, duration::CFDuration};

#[derive(Debug, PartialEq)]
pub enum Unit {
    Year,
    Month,
    Day,
    Hour,
    Minute,
    Second,
    Millisecond,
    Microsecond,
    Nanosecond,
}

impl Unit {
    pub fn to_duration(&self, calendar: Calendar) -> CFDuration {
        match self {
            Unit::Year => CFDuration::from_years(1, calendar),
            Unit::Month => CFDuration::from_months(1, calendar),
            Unit::Day => CFDuration::from_days(1, calendar),
            Unit::Hour => CFDuration::from_hours(1, calendar),
            Unit::Minute => CFDuration::from_minutes(1, calendar),
            Unit::Second => CFDuration::from_seconds(1, calendar),
            Unit::Millisecond => CFDuration::from_milliseconds(1, calendar),
            Unit::Microsecond => CFDuration::from_microseconds(1, calendar),
            Unit::Nanosecond => CFDuration::from_nanoseconds(1, calendar),
        }
    }
}
#[derive(Debug)]
pub struct ParsedDatetime {
    pub ymd: (i64, u8, u8),
    pub hms: Option<(u8, u8, f32)>,
    pub tz: Option<(i8, u8)>,
    pub nanosecond: Option<i64>,
}
#[derive(Debug)]
pub struct ParsedCFTime {
    pub unit: Unit,
    pub datetime: ParsedDatetime,
}
pub fn parse_cf_time(unit: &str) -> Result<ParsedCFTime, crate::errors::Error> {
    let matches: Vec<&str> = unit.split(' ').collect();
    if matches.len() < 3 {
        return Err(crate::errors::Error::UnitParserError(unit.to_string()));
    }

    let duration_unit = match matches[0] {
        "common_years" | "common_year" => Unit::Year,
        "months" | "month" => Unit::Month,
        "days" | "day" | "d" => Unit::Day,
        "hours" | "hour" | "hrs" | "hr" | "h" => Unit::Hour,
        "minutes" | "minute" | "mins" | "min" => Unit::Minute,
        "seconds" | "second" | "secs" | "sec" | "s" => Unit::Second,
        "milliseconds" | "millisecond" | "millisecs" | "millisec" | "msecs" | "msec" | "ms" => {
            Unit::Millisecond
        }
        "microseconds" | "microsecond" | "microsecs" | "microsec" => Unit::Microsecond,
        _ => {
            return Err(crate::errors::Error::UnitParserError(
                format!("Invalid duration unit: {unit}").to_string(),
            ))
        }
    };

    if matches[1] != "since" {
        return Err(crate::errors::Error::UnitParserError(
            format!("Expected 'since' found : '{}'", matches[1]).to_string(),
        ));
    }

    let date: Vec<&str> = matches[2].split('-').collect();
    if date.len() != 3 {
        return Err(crate::errors::Error::UnitParserError(
            format!("Invalid date: {unit}").to_string(),
        ));
    }
    let year = date[0].parse::<i64>()?;
    let month = date[1].parse::<u8>()?;
    let day = date[2].parse::<u8>()?;

    if matches.len() <= 3 {
        return Ok(ParsedCFTime {
            unit: duration_unit,
            datetime: ParsedDatetime {
                ymd: (year, month, day),
                hms: None,
                tz: None,
                nanosecond: None,
            },
        });
    }

    let time: Vec<&str> = matches[3].split(':').collect();
    if time.len() != 3 {
        return Err(crate::errors::Error::UnitParserError(
            format!("Invalid time: {unit}").to_string(),
        ));
    }
    let hour = time[0].parse::<u8>()?;
    let minute = time[1].parse::<u8>()?;
    let second = time[2].parse::<f32>()?;

    if matches.len() <= 4 {
        return Ok(ParsedCFTime {
            unit: duration_unit,
            datetime: ParsedDatetime {
                ymd: (year, month, day),
                hms: Some((hour, minute, second)),
                tz: None,
                nanosecond: None,
            },
        });
    }

    let tz: Vec<&str> = matches[4].split(':').collect();
    if tz.len() != 2 {
        return Err(crate::errors::Error::UnitParserError(
            format!("Invalid time zone: {unit}").to_string(),
        ));
    }
    let tzhour = tz[0].parse::<i8>()?;
    let tzminute = tz[1].parse::<u8>()?;
    Ok(ParsedCFTime {
        unit: duration_unit,
        datetime: ParsedDatetime {
            ymd: (year, month, day),
            hms: Some((hour, minute, second)),
            tz: Some((tzhour, tzminute)),
            nanosecond: None,
        },
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_valid_duration_units() {
        // Test valid duration units
        let units = vec![
            ("common_years since 2023-01-01", Unit::Year),
            ("months since 2023-01-01", Unit::Month),
            ("day since 2023-01-01", Unit::Day),
            // Add more valid units here
        ];

        for (input, expected_unit) in units {
            let result = parse_cf_time(input).unwrap();
            assert!(result.unit == expected_unit);
            assert_eq!(result.datetime.ymd, (2023, 1, 1));
            assert_eq!(result.datetime.hms, None);
            assert_eq!(result.datetime.tz, None);
            assert_eq!(result.datetime.nanosecond, None);
        }
    }

    #[test]
    fn test_valid_date_time_units() {
        // Test valid date and time units with different combinations
        let units = vec![
            // From CF conventions
            (
                "seconds since 1992-10-8 15:15:42.5 -6:00",
                ParsedCFTime {
                    unit: Unit::Second,
                    datetime: ParsedDatetime {
                        ymd: (1992, 10, 8),
                        hms: Some((15, 15, 42.5)),
                        tz: Some((-6, 0)),
                        nanosecond: None,
                    },
                },
            ),
            // Date, no time, no timezone
            (
                "seconds since 1992-10-08",
                ParsedCFTime {
                    unit: Unit::Second,
                    datetime: ParsedDatetime {
                        ymd: (1992, 10, 8),
                        hms: None,
                        tz: None,
                        nanosecond: None,
                    },
                },
            ),
            (
                "minutes since 2000-01-01",
                ParsedCFTime {
                    unit: Unit::Minute,
                    datetime: ParsedDatetime {
                        ymd: (2000, 1, 1),
                        hms: None,
                        tz: None,
                        nanosecond: None,
                    },
                },
            ),
            (
                "hour since 1985-12-31",
                ParsedCFTime {
                    unit: Unit::Hour,
                    datetime: ParsedDatetime {
                        ymd: (1985, 12, 31),
                        hms: None,
                        tz: None,
                        nanosecond: None,
                    },
                },
            ),
            // Date and time, no timezone
            (
                "seconds since 2022-11-30 10:15:20",
                ParsedCFTime {
                    unit: Unit::Second,
                    datetime: ParsedDatetime {
                        ymd: (2022, 11, 30),
                        hms: Some((10, 15, 20.0)),
                        tz: None,
                        nanosecond: None,
                    },
                },
            ),
            (
                "minutes since 2010-05-15 05:30:00",
                ParsedCFTime {
                    unit: Unit::Minute,
                    datetime: ParsedDatetime {
                        ymd: (2010, 5, 15),
                        hms: Some((5, 30, 0.0)),
                        tz: None,
                        nanosecond: None,
                    },
                },
            ),
            (
                "hour since 1999-03-20 12:00:01",
                ParsedCFTime {
                    unit: Unit::Hour,
                    datetime: ParsedDatetime {
                        ymd: (1999, 3, 20),
                        hms: Some((12, 0, 1.0)),
                        tz: None,
                        nanosecond: None,
                    },
                },
            ),
            // Date, time, and timezone
            (
                "seconds since 2015-07-04 16:45:30 +02:30",
                ParsedCFTime {
                    unit: Unit::Second,
                    datetime: ParsedDatetime {
                        ymd: (2015, 7, 4),
                        hms: Some((16, 45, 30.0)),
                        tz: Some((2, 30)),
                        nanosecond: None,
                    },
                },
            ),
            (
                "minutes since 2023-12-25 08:00:00 -05:00",
                ParsedCFTime {
                    unit: Unit::Minute,
                    datetime: ParsedDatetime {
                        ymd: (2023, 12, 25),
                        hms: Some((8, 0, 0.0)),
                        tz: Some((-5, 0)),
                        nanosecond: None,
                    },
                },
            ),
            (
                "hour since 2018-09-10 00:00:00 -03:30",
                ParsedCFTime {
                    unit: Unit::Hour,
                    datetime: ParsedDatetime {
                        ymd: (2018, 9, 10),
                        hms: Some((0, 0, 0.0)),
                        tz: Some((-3, 30)),
                        nanosecond: None,
                    },
                },
            ),
        ];

        for (input, expected_unit) in units {
            let result = parse_cf_time(input).unwrap();
            assert!(result.unit == expected_unit.unit);
            assert_eq!(result.datetime.ymd, expected_unit.datetime.ymd);
            assert_eq!(result.datetime.hms, expected_unit.datetime.hms);
            assert_eq!(result.datetime.tz, expected_unit.datetime.tz);
            assert_eq!(
                result.datetime.nanosecond,
                expected_unit.datetime.nanosecond
            );
        }
    }
    #[test]
    fn test_not_valid_date_time_units() {
        // Test valid date and time units with different combinations
        let units = vec![
            "seconds since 2019-06-15 -07:00",
            "nanoseconds since 2020-01-01 9876543210", // nanoseconds not permitted
            "invalid_unit since 2023-01-01",           // Invalid unit
            "hou since 2023-01-01",                    // Missing 'rs' in 'hours'
            "minutes 2023-01-01",                      // Missing 'since'
        ];

        for input in units {
            let result = parse_cf_time(input);
            assert!(matches!(
                result.err().unwrap(),
                crate::errors::Error::UnitParserError(_)
            ))
        }
    }
    // Add more tests for different valid date and time scenarios
}