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
use std::ops::{Add, Div, Mul, Neg, Sub};

use chrono::{DateTime as CrDateTime, Months, Utc};

use crate::{DateTime, Time, TimeDelta, TimeUnitTrait};

// TODO: improve performance for time operation

impl<U: TimeUnitTrait> Add<TimeDelta> for DateTime<U>
where
    Self: From<CrDateTime<Utc>> + TryInto<CrDateTime<Utc>>,
{
    type Output = DateTime<U>;
    fn add(self, rhs: TimeDelta) -> Self::Output {
        if self.is_not_nat() && rhs.is_not_nat() {
            let dt = self.as_cr().unwrap();
            let out = if rhs.months != 0 {
                if rhs.months > 0 {
                    dt + Months::new(rhs.months as u32)
                } else {
                    dt - Months::new((-rhs.months) as u32)
                }
            } else {
                dt
            };
            (out + rhs.inner).into()
        } else {
            DateTime::nat()
        }
    }
}

impl<U: TimeUnitTrait> Sub<TimeDelta> for DateTime<U>
where
    Self: From<CrDateTime<Utc>> + TryInto<CrDateTime<Utc>>,
{
    type Output = DateTime<U>;
    fn sub(self, rhs: TimeDelta) -> Self::Output {
        if self.is_not_nat() && rhs.is_not_nat() {
            let dt = self.as_cr().unwrap();
            let out = if rhs.months != 0 {
                if rhs.months > 0 {
                    dt - Months::new(rhs.months as u32)
                } else {
                    dt + Months::new((-rhs.months) as u32)
                }
            } else {
                dt
            };
            (out - rhs.inner).into()
        } else {
            DateTime::nat()
        }
    }
}

impl<U: TimeUnitTrait> Sub<DateTime<U>> for DateTime<U>
where
    Self: From<CrDateTime<Utc>> + TryInto<CrDateTime<Utc>>,
{
    type Output = TimeDelta;
    fn sub(self, rhs: DateTime<U>) -> Self::Output {
        // TODO: improve performance
        // this can be done by implement unit conversion
        if self.is_not_nat() && rhs.is_not_nat() {
            let dt1 = self.as_cr().unwrap();
            let dt2 = rhs.as_cr().unwrap();
            let duration = dt1 - dt2;
            TimeDelta {
                months: 0,
                inner: duration,
            }
            // let r_year = dt2.year();
            // let years = dt1.year() - r_year;
            // let months = dt1.month() as i32 - dt2.month() as i32;
            // let duration =
            //     dt1.with_year(r_year).expect(&format!("{dt1} with {r_year}")).with_month(1).expect(&format!("{dt1} with month1")) - dt2.with_month(1).expect(&format!("{dt2} with month1"));
            // TimeDelta {
            //     months: 12 * years + months,
            //     inner: duration,
            // }
        } else {
            TimeDelta::nat()
        }
    }
}

impl Neg for TimeDelta {
    type Output = TimeDelta;

    #[inline]
    fn neg(self) -> TimeDelta {
        if self.is_not_nat() {
            Self {
                months: -self.months,
                inner: -self.inner,
            }
        } else {
            self
        }
    }
}

impl Add for TimeDelta {
    type Output = TimeDelta;
    #[inline]
    fn add(self, rhs: TimeDelta) -> TimeDelta {
        if self.is_not_nat() & rhs.is_not_nat() {
            Self {
                months: self.months + rhs.months,
                inner: self.inner + rhs.inner,
            }
        } else {
            TimeDelta::nat()
        }
    }
}

impl Sub for TimeDelta {
    type Output = TimeDelta;
    #[inline]
    fn sub(self, rhs: TimeDelta) -> TimeDelta {
        if self.is_not_nat() & rhs.is_not_nat() {
            Self {
                months: self.months - rhs.months,
                inner: self.inner - rhs.inner,
            }
        } else {
            TimeDelta::nat()
        }
    }
}

impl Mul<i32> for TimeDelta {
    type Output = TimeDelta;
    #[inline]
    fn mul(self, rhs: i32) -> Self {
        if self.is_not_nat() {
            Self {
                months: self.months * rhs,
                inner: self.inner * rhs,
            }
        } else {
            TimeDelta::nat()
        }
    }
}

impl Div<TimeDelta> for TimeDelta {
    type Output = i32;

    fn div(self, rhs: TimeDelta) -> Self::Output {
        if self.is_not_nat() & rhs.is_not_nat() {
            // may not as expected
            let inner_div =
                self.inner.num_nanoseconds().unwrap() / rhs.inner.num_nanoseconds().unwrap();
            if self.months == 0 || rhs.months == 0 {
                return inner_div as i32;
            }
            let month_div = self.months / rhs.months;
            if month_div == inner_div as i32 {
                month_div
            } else {
                panic!("not support div TimeDelta when month div and time div is not equal")
            }
        } else {
            panic!("not support div TimeDelta when one of them is nat")
        }
    }
}

impl Add<TimeDelta> for Time {
    type Output = Time;
    fn add(self, rhs: TimeDelta) -> Self::Output {
        if rhs.is_not_nat() {
            if rhs.months != 0 {
                panic!("not support add TimeDelta with months");
            }
            if let Some(nanos) = rhs.inner.num_nanoseconds() {
                let nanos = self.0 + nanos;
                return Time(nanos);
            }
        }
        Time::nat()
    }
}

impl Sub<TimeDelta> for Time {
    type Output = Time;
    fn sub(self, rhs: TimeDelta) -> Self::Output {
        if rhs.is_not_nat() {
            if rhs.months != 0 {
                panic!("not support sub TimeDelta with months");
            }
            if let Some(nanos) = rhs.inner.num_nanoseconds() {
                let nanos = self.0 - nanos;
                return Time(nanos);
            }
        }
        Time::nat()
    }
}

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

    #[test]
    fn test_time_add_timedelta() {
        let time = Time::from_hms(12, 0, 0);
        let delta = TimeDelta::parse("1h30m").unwrap();
        let result = time + delta;
        assert_eq!(result, Time::from_hms(13, 30, 0));
    }

    #[test]
    fn test_time_sub_timedelta() {
        let time = Time::from_hms(12, 0, 0);
        let delta = TimeDelta::parse("1h30m").unwrap();
        let result = time - delta;
        assert_eq!(result, Time::from_hms(10, 30, 0));
    }

    #[test]
    #[should_panic]
    fn test_time_add_timedelta_with_months() {
        let time = Time::from_hms(12, 0, 0);
        let delta = TimeDelta::parse("1mo1h30m").unwrap();
        let _ = time + delta;
    }

    #[test]
    #[should_panic]
    fn test_time_sub_timedelta_with_months() {
        let time = Time::from_hms(12, 0, 0);
        let delta = TimeDelta::parse("1mo1h30m").unwrap();
        let _ = time - delta;
    }

    #[test]
    fn test_time_add_nat_timedelta() {
        let time = Time::from_hms(12, 0, 0);
        let nat_delta = TimeDelta::nat();
        let result = time + nat_delta;
        assert_eq!(result, Time::nat());
    }

    #[test]
    fn test_time_sub_nat_timedelta() {
        let time = Time::from_hms(12, 0, 0);
        let nat_delta = TimeDelta::nat();
        let result = time - nat_delta;
        assert_eq!(result, Time::nat());
    }
}