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
#[cfg(feature = "std")]
use core::fmt::{Debug, Display, Formatter};
use core::ops::Deref;

#[cfg(feature = "arrow")]
use arrow2::{
    array::MutablePrimitiveArray,
    datatypes::{DataType, TimeUnit},
};
#[cfg(feature = "arrow")]
use arrow2_convert::{field::ArrowField, serialize::ArrowSerialize};
use bincode::BorrowDecode;
#[cfg(feature = "std")]
use bincode::{Decode, Encode};
#[cfg(feature = "pg")]
use postgres_types::{FromSql, ToSql};
use rapira::{Rapira, RapiraError};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use serde_json::Value as JsonValue;
#[cfg(feature = "ts-types")]
use specta::Type;
#[cfg(feature = "std")]
use thiserror::Error;
#[cfg(feature = "std")]
use time::format_description::well_known::Rfc3339;
use time::{Duration as TimeDuration, OffsetDateTime};
#[cfg(feature = "ts-types")]
use typescript_type_def::{
    type_expr::{DefinedTypeInfo, Docs, Ident, TypeDefinition, TypeExpr, TypeInfo},
    TypeDef,
};
#[cfg(feature = "wa_proto")]
use wa_proto::{Incoming, Outcoming};

use crate::{GetType, Typ, Value};

#[cfg_attr(feature = "std", derive(Error, Debug))]
pub enum DatetimeError {
    #[cfg_attr(feature = "std", error("string parse error"))]
    ParseError,
    #[cfg_attr(feature = "std", error("json parse error"))]
    JsonError,
}

/// i64 stored type, ISO 8601 json type
#[derive(PartialEq, Clone, Copy, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "std", derive(Deserialize, Debug))]
#[cfg_attr(feature = "ts-types", derive(Type))]
#[cfg_attr(feature = "wa_proto", derive(Outcoming, Incoming))]
#[cfg_attr(feature = "pg", derive(FromSql, ToSql))]
#[cfg_attr(feature = "pg", postgres(transparent))]
#[repr(transparent)]
pub struct Datetime(OffsetDateTime);

impl Datetime {
    pub fn new(dt: OffsetDateTime) -> Self {
        Self(dt)
    }

    #[cfg(feature = "std")]
    pub fn now() -> Self {
        Self(OffsetDateTime::now_utc())
    }

    pub fn get_native_dt(&self) -> OffsetDateTime {
        self.0
    }

    /// 1985-04-12T23:20:50.52Z
    #[cfg(feature = "std")]
    pub fn to_str(self) -> String {
        let dt = self.0.replace_millisecond(0).unwrap();
        dt.format(&Rfc3339).expect("cannot format datetime")
    }

    /// json string "1985-04-12T23:20:50.52Z"
    #[cfg(feature = "std")]
    pub fn to_json(self) -> JsonValue {
        JsonValue::String(self.to_str())
    }

    /// from string "1985-04-12T23:20:50.52Z"
    #[cfg(feature = "std")]
    pub fn from_string(value: &str) -> Result<Self, DatetimeError> {
        OffsetDateTime::parse(value, &Rfc3339)
            .map(Datetime)
            .map_err(|_| DatetimeError::ParseError)
    }

    /// from json string "1985-04-12T23:20:50.52Z"
    #[cfg(feature = "std")]
    pub fn from_json(value: JsonValue) -> Result<Self, DatetimeError> {
        if let JsonValue::String(s) = value {
            Self::from_string(&s)
        } else {
            Err(DatetimeError::JsonError)
        }
    }

    /// milliseconds timestamp
    #[inline]
    pub fn to_i64(self) -> i64 {
        // unix_timestamp - seconds * 100 = milliseconds
        let ts = self.0.unix_timestamp() * 1000;
        let ms = self.0.millisecond();
        ts + ms as i64
    }

    /// from milliseconds timestamp
    #[inline]
    pub fn from_i64(i: i64) -> Result<Self, time::error::ComponentRange> {
        // milliseconds
        let ms = i % 1000;
        // seconds
        let ts = i / 1000;
        let dt = OffsetDateTime::from_unix_timestamp(ts)? + TimeDuration::milliseconds(ms);
        Ok(Datetime(dt))
    }
}

impl Default for Datetime {
    fn default() -> Self {
        #[cfg(feature = "std")]
        let created = OffsetDateTime::now_utc();

        #[cfg(not(feature = "std"))]
        let created = OffsetDateTime::UNIX_EPOCH;

        Datetime(created)
    }
}

#[cfg(feature = "std")]
impl Serialize for Datetime {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let s = self.to_str();
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "std")]
impl Display for Datetime {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_str())
    }
}

impl Deref for Datetime {
    type Target = OffsetDateTime;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(feature = "std")]
impl Encode for Datetime {
    fn encode<E: bincode::enc::Encoder>(
        &self,
        encoder: &mut E,
    ) -> core::result::Result<(), bincode::error::EncodeError> {
        let tsm = self.to_i64();
        bincode::Encode::encode(&tsm, encoder)?;
        Ok(())
    }
}

#[cfg(feature = "std")]
impl Decode for Datetime {
    fn decode<D: bincode::de::Decoder>(
        decoder: &mut D,
    ) -> Result<Self, bincode::error::DecodeError> {
        let tsm: i64 = bincode::de::Decode::decode(decoder)?;
        Self::from_i64(tsm).map_err(|_| {
            bincode::error::DecodeError::OtherString(
                "OffsetDateTime::from_unix_timestamp error".to_owned(),
            )
        })
    }
}

impl<'de> BorrowDecode<'de> for Datetime {
    fn borrow_decode<D: bincode::de::BorrowDecoder<'de>>(
        decoder: &mut D,
    ) -> Result<Self, bincode::error::DecodeError> {
        let tsm: i64 = bincode::de::Decode::decode(decoder)?;
        Self::from_i64(tsm).map_err(|_| {
            bincode::error::DecodeError::OtherString(
                "OffsetDateTime::from_unix_timestamp error".to_owned(),
            )
        })
    }
}

impl Rapira for Datetime {
    const STATIC_SIZE: Option<usize> = Some(8);

    #[inline]
    fn from_slice(slice: &mut &[u8]) -> Result<Self, rapira::RapiraError>
    where
        Self: Sized,
    {
        let i = i64::from_slice(slice)?;
        Self::from_i64(i).map_err(|_| RapiraError::DatetimeError)
    }

    #[inline]
    fn check_bytes(slice: &mut &[u8]) -> Result<(), rapira::RapiraError>
    where
        Self: Sized,
    {
        let i = i64::from_slice(slice)?;
        // seconds
        let ts = i / 1000;
        OffsetDateTime::from_unix_timestamp(ts).map_err(|_| RapiraError::DatetimeError)?;
        Ok(())
    }

    #[inline]
    unsafe fn from_slice_unsafe(slice: &mut &[u8]) -> Result<Self, rapira::RapiraError>
    where
        Self: Sized,
    {
        let u = i64::from_slice_unsafe(slice)?;
        Self::from_i64(u).map_err(|_| RapiraError::DatetimeError)
    }

    #[inline]
    fn convert_to_bytes(&self, slice: &mut [u8], cursor: &mut usize) {
        let tsm = self.to_i64();
        tsm.convert_to_bytes(slice, cursor);
    }

    #[inline]
    fn size(&self) -> usize {
        8
    }
}

impl GetType for Datetime {
    // TODO: datetime type?
    const TYPE: Typ = Typ::Datetime;
}

// impl TryFrom<Value> for Datetime {
//     type Error = FromValueError;
//     fn try_from(value: Value) -> Result<Self, Self::Error> {
//         <OffsetDateTime as TryFrom<Value>>::try_from(value)
//             .map(Datetime)
//             .map_err(|_| FromValueError::TimeParseError)
//     }
// }
// impl TryFromValue for Datetime {
//     fn try_from(value: Value) -> Result<Self, FromValueError> {
//         <OffsetDateTime as TryFromValue>::try_from(value).map(Datetime)
//     }
// }

impl From<Datetime> for Value {
    fn from(val: Datetime) -> Self {
        Value::from(val.get_native_dt())
    }
}

#[cfg(feature = "ts-types")]
impl TypeDef for Datetime {
    const INFO: TypeInfo = TypeInfo::Defined(DefinedTypeInfo {
        def: TypeDefinition {
            docs: Some(Docs("1985-04-12T23:20:50.52Z")),
            path: &[],
            name: Ident("Datetime"),
            generic_vars: &[],
            def: TypeExpr::Ref(&String::INFO),
        },
        generic_args: &[],
    });
}

#[cfg(feature = "arrow")]
impl ArrowField for Datetime {
    type Type = Datetime;

    fn data_type() -> DataType {
        DataType::Timestamp(TimeUnit::Millisecond, None)
    }
}

#[cfg(feature = "arrow")]
impl ArrowSerialize for Datetime {
    type MutableArrayType = MutablePrimitiveArray<i64>;

    fn new_array() -> Self::MutableArrayType {
        MutablePrimitiveArray::new()
    }

    fn arrow_serialize(
        v: &<Self as ArrowField>::Type,
        array: &mut Self::MutableArrayType,
    ) -> arrow2::error::Result<()> {
        array.push(Some(v.to_i64()));
        Ok(())
    }
}

// #[cfg(feature = "pg")]
// impl From<Datetime> for PgTimestamp {
//     fn from(v: Datetime) -> Self {
//         let unix = v.0.unix_timestamp();
//         PgTimestamp(unix * 1_000_000)
//     }
// }