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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

//! A collection of utilities for representing and working with dates as an input to
//! formatting operations.

use crate::calendar::CldrCalendar;

use crate::provider::time_zones::{MetaZoneId, TimeZoneBcp47Id};
use icu_calendar::{arithmetic::week_of, AsCalendar, Date, DateTime};
use icu_locid::Locale;
use tinystr::TinyStr8;

// TODO (Manishearth) fix up imports to directly import from icu_calendar
pub use icu_calendar::types::*;
pub use icu_calendar::DateTimeError;

/// Representation of a formattable calendar date. Supports dates in any calendar system that uses
/// solar days indexed by an era, year, month, and day.
///
/// All fields are optional. If a field is not present but is required when formatting, an error
/// result will be returned from the formatter.
///
/// All data represented in [`DateInput`] should be locale-agnostic.
pub trait DateInput {
    /// The CLDR calendar this date relates to
    type Calendar: CldrCalendar;
    /// Gets the era and year input.
    fn year(&self) -> Option<Year>;

    /// Gets the month input.
    fn month(&self) -> Option<Month>;

    /// Gets the day input.
    fn day_of_month(&self) -> Option<DayOfMonth>;

    /// Gets the weekday input.
    fn iso_weekday(&self) -> Option<IsoWeekday>;

    /// Gets information on the position of the day within the year.
    fn day_of_year_info(&self) -> Option<DayOfYearInfo>;
}

/// Representation of a time of day according to ISO-8601 conventions. Always indexed from
/// midnight, regardless of calendar system.
///
/// All fields are optional. If a field is not present but is required when formatting, an error
/// result will be returned from the formatter.
///
/// All data represented in [`IsoTimeInput`] should be locale-agnostic.
pub trait IsoTimeInput {
    /// Gets the hour input.
    fn hour(&self) -> Option<IsoHour>;

    /// Gets the minute input.
    fn minute(&self) -> Option<IsoMinute>;

    /// Gets the second input.
    fn second(&self) -> Option<IsoSecond>;

    /// Gets the nanosecond input.
    fn nanosecond(&self) -> Option<NanoSecond>;
}

/// Representation of a formattable time zone.
///
/// Only the [`GmtOffset`] is required, since it is the final format fallback.
///
/// All data represented in [`TimeZoneInput`] should be locale-agnostic.
pub trait TimeZoneInput {
    /// The GMT offset in Nanoseconds.
    fn gmt_offset(&self) -> GmtOffset;

    /// The IANA time-zone identifier.
    fn time_zone_id(&self) -> Option<&TimeZoneBcp47Id>;

    /// The metazone identifier.
    fn metazone_id(&self) -> Option<&MetaZoneId>;

    /// The time variant (e.g. "daylight", "standard")
    fn time_variant(&self) -> Option<&TinyStr8>;
}

/// A combination of a formattable calendar date and ISO time.
pub trait DateTimeInput: DateInput + IsoTimeInput {}

/// A combination of a formattable calendar date, ISO time, and time zone.
pub trait ZonedDateTimeInput: TimeZoneInput + DateTimeInput {}

impl<T> DateTimeInput for T where T: DateInput + IsoTimeInput {}
impl<T> ZonedDateTimeInput for T where T: TimeZoneInput + DateTimeInput {}

/// A formattable calendar date and ISO time that takes the locale into account.
pub trait LocalizedDateTimeInput<T: DateTimeInput> {
    /// A reference to this instance's [`DateTimeInput`].
    fn datetime(&self) -> &T;

    /// The year number according to week numbering.
    ///
    /// For example, December 31, 2020 is part of the first week of 2021.
    fn year_week(&self) -> Result<Year, DateTimeError>;

    /// The week of the month.
    ///
    /// For example, January 1, 2021 is part of the first week of January.
    fn week_of_month(&self) -> Result<WeekOfMonth, DateTimeError>;

    /// The week number of the year.
    ///
    /// For example, December 31, 2020 is part of the first week of 2021.
    fn week_of_year(&self) -> Result<WeekOfYear, DateTimeError>;

    /// The day of week in this month.
    ///
    /// For example, July 8, 2020 is the 2nd Wednesday of July.
    fn day_of_week_in_month(&self) -> Result<DayOfWeekInMonth, DateTimeError>;

    /// TODO(#487): Implement flexible day periods.
    fn flexible_day_period(&self);
}

pub(crate) struct DateTimeInputWithLocale<'data, T: DateTimeInput> {
    data: &'data T,
    calendar: Option<&'data week_of::CalendarInfo>,
}

fn compute_week_of_year<T: DateInput>(
    datetime: &T,
    calendar: &week_of::CalendarInfo,
) -> Result<(DayOfYearInfo, week_of::WeekOf), DateTimeError> {
    let doy_info = datetime
        .day_of_year_info()
        .ok_or(DateTimeError::MissingInput(
            "DateTimeInput::day_of_year_info",
        ))?;
    let week = week_of::week_of(
        calendar,
        doy_info.days_in_prev_year as u16,
        doy_info.days_in_year as u16,
        doy_info.day_of_year as u16,
        datetime
            .iso_weekday()
            .ok_or(DateTimeError::MissingInput("DateTimeInput::iso_weekday"))?,
    )?;
    Ok((doy_info, week))
}

fn year_week<T: DateInput>(
    datetime: &T,
    calendar: &week_of::CalendarInfo,
) -> Result<Year, DateTimeError> {
    let (doy_info, week) = compute_week_of_year(datetime, calendar)?;
    Ok(match week.unit {
        week_of::RelativeUnit::Previous => doy_info.prev_year,
        week_of::RelativeUnit::Current => datetime
            .year()
            .ok_or(DateTimeError::MissingInput("DateTimeInput::year"))?,
        week_of::RelativeUnit::Next => doy_info.next_year,
    })
}

fn week_of_year<T: DateInput>(
    datetime: &T,
    calendar: &week_of::CalendarInfo,
) -> Result<WeekOfYear, DateTimeError> {
    let (_, week) = compute_week_of_year(datetime, calendar)?;
    Ok(WeekOfYear(u32::from(week.week)))
}

/// Returns the week of month according to a calendar with min_week_days = 1.
///
/// This is different from what the UTS35 spec describes [1] but the latter is
/// missing a month of week-of-month field so following the spec would result
/// in inconsistencies (e.g. in the ISO calendar 2021-01-01 is the last week
/// of December but 'MMMMW' would have it formatted as 'week 5 of January').
///
/// 1: https://www.unicode.org/reports/tr35/tr35-55/tr35-dates.html#Date_Patterns_Week_Of_Year
fn week_of_month<T: DateInput>(
    datetime: &T,
    first_weekday: IsoWeekday,
) -> Result<WeekOfMonth, DateTimeError> {
    let day_of_month = datetime
        .day_of_month()
        .ok_or(DateTimeError::MissingInput("DateTimeInput::day_of_month"))?;

    let week = week_of::simple_week_of(
        first_weekday,
        day_of_month.0 as u16,
        datetime
            .iso_weekday()
            .ok_or(DateTimeError::MissingInput("DateTimeInput::iso_weekday"))?,
    );
    Ok(WeekOfMonth(u32::from(week)))
}

fn day_of_week_in_month<T: DateInput>(datetime: &T) -> Result<DayOfWeekInMonth, DateTimeError> {
    let day_of_month = datetime
        .day_of_month()
        .ok_or(DateTimeError::MissingInput("DateTimeInput::day_of_month"))?;
    Ok(day_of_month.into())
}

impl<'data, T: DateTimeInput> DateTimeInputWithLocale<'data, T> {
    pub fn new(
        data: &'data T,
        calendar: Option<&'data week_of::CalendarInfo>,
        _locale: &Locale,
    ) -> Self {
        Self { data, calendar }
    }
}

pub(crate) struct ZonedDateTimeInputWithLocale<'data, T: ZonedDateTimeInput> {
    data: &'data T,
    calendar: Option<&'data week_of::CalendarInfo>,
}

impl<'data, T: ZonedDateTimeInput> ZonedDateTimeInputWithLocale<'data, T> {
    pub fn new(
        data: &'data T,
        calendar: Option<&'data week_of::CalendarInfo>,
        _locale: &Locale,
    ) -> Self {
        Self { data, calendar }
    }
}

impl<'data, T: DateTimeInput> LocalizedDateTimeInput<T> for DateTimeInputWithLocale<'data, T> {
    fn datetime(&self) -> &T {
        self.data
    }

    fn year_week(&self) -> Result<Year, DateTimeError> {
        year_week(
            self.data,
            #[allow(clippy::expect_used)]
            // TODO(#1668) Clippy exceptions need docs or fixing.
            self.calendar
                .expect("calendar must be provided when using week of methods"),
        )
    }

    fn week_of_month(&self) -> Result<WeekOfMonth, DateTimeError> {
        #[allow(clippy::expect_used)] // TODO(#1668) Clippy exceptions need docs or fixing.
        week_of_month(
            self.data,
            self.calendar
                .expect("calendar must be provided when using week of methods")
                .first_weekday,
        )
    }

    fn week_of_year(&self) -> Result<WeekOfYear, DateTimeError> {
        week_of_year(
            self.data,
            #[allow(clippy::expect_used)]
            // TODO(#1668) Clippy exceptions need docs or fixing.
            self.calendar
                .expect("calendar must be provided when using week of methods"),
        )
    }

    fn day_of_week_in_month(&self) -> Result<DayOfWeekInMonth, DateTimeError> {
        day_of_week_in_month(self.data)
    }

    fn flexible_day_period(&self) {
        todo!("#487")
    }
}

impl<'data, T: ZonedDateTimeInput> LocalizedDateTimeInput<T>
    for ZonedDateTimeInputWithLocale<'data, T>
{
    fn datetime(&self) -> &T {
        self.data
    }

    fn year_week(&self) -> Result<Year, DateTimeError> {
        year_week(
            self.data,
            #[allow(clippy::expect_used)] // TODO(#1668) Clippy exceptions need docs or fixing.
            self.calendar
                .expect("calendar must be provided when using week of methods"),
        )
    }

    fn week_of_month(&self) -> Result<WeekOfMonth, DateTimeError> {
        #[allow(clippy::expect_used)] // TODO(#1668) Clippy exceptions need docs or fixing.
        week_of_month(
            self.data,
            self.calendar
                .expect("calendar must be provided when using week of methods")
                .first_weekday,
        )
    }

    fn week_of_year(&self) -> Result<WeekOfYear, DateTimeError> {
        week_of_year(
            self.data,
            #[allow(clippy::expect_used)] // TODO(#1668) Clippy exceptions need docs or fixing.
            self.calendar
                .expect("calendar must be provided when using week of methods"),
        )
    }

    fn day_of_week_in_month(&self) -> Result<DayOfWeekInMonth, DateTimeError> {
        day_of_week_in_month(self.data)
    }

    fn flexible_day_period(&self) {
        todo!("#487")
    }
}

impl<C: CldrCalendar, A: AsCalendar<Calendar = C>> DateInput for Date<A> {
    type Calendar = C;
    /// Gets the era and year input.
    fn year(&self) -> Option<Year> {
        Some(self.year())
    }

    /// Gets the month input.
    fn month(&self) -> Option<Month> {
        Some(self.month())
    }

    /// Gets the day input.
    fn day_of_month(&self) -> Option<DayOfMonth> {
        Some(self.day_of_month())
    }

    /// Gets the weekday input.
    fn iso_weekday(&self) -> Option<IsoWeekday> {
        Some(self.day_of_week())
    }

    /// Gets information on the position of the day within the year.
    fn day_of_year_info(&self) -> Option<DayOfYearInfo> {
        Some(self.day_of_year_info())
    }
}

impl<C: CldrCalendar, A: AsCalendar<Calendar = C>> DateInput for DateTime<A> {
    type Calendar = C;
    /// Gets the era and year input.
    fn year(&self) -> Option<Year> {
        Some(self.date.year())
    }

    /// Gets the month input.
    fn month(&self) -> Option<Month> {
        Some(self.date.month())
    }

    /// Gets the day input.
    fn day_of_month(&self) -> Option<DayOfMonth> {
        Some(self.date.day_of_month())
    }

    /// Gets the weekday input.
    fn iso_weekday(&self) -> Option<IsoWeekday> {
        Some(self.date.day_of_week())
    }

    /// Gets information on the position of the day within the year.
    fn day_of_year_info(&self) -> Option<DayOfYearInfo> {
        Some(self.date.day_of_year_info())
    }
}

impl<A: AsCalendar> IsoTimeInput for DateTime<A> {
    /// Gets the hour input.
    fn hour(&self) -> Option<IsoHour> {
        Some(self.time.hour)
    }

    /// Gets the minute input.
    fn minute(&self) -> Option<IsoMinute> {
        Some(self.time.minute)
    }

    /// Gets the second input.
    fn second(&self) -> Option<IsoSecond> {
        Some(self.time.second)
    }

    /// Gets the fractional second input.
    fn nanosecond(&self) -> Option<NanoSecond> {
        Some(self.time.nanosecond)
    }
}