use chrono::prelude::*;
use chrono_tz::Tz;

use crate::types::{DateTimeType, SqlType, Value, ValueRef};

pub trait DateConverter {
    fn to_date(&self, tz: Tz) -> ValueRef<'static>;
    fn get_stamp(source: Value) -> Self;
    fn date_type() -> SqlType;

    fn get_days(date: NaiveDate) -> u16 {
        const UNIX_EPOCH_DAY: i64 = 719_163;
        let gregorian_day = i64::from(date.num_days_from_ce());
        (gregorian_day - UNIX_EPOCH_DAY) as u16
    }
}

impl DateConverter for u16 {
    fn to_date(&self, _tz: Tz) -> ValueRef<'static> {
        ValueRef::Date(*self)
    }

    fn get_stamp(source: Value) -> Self {
        Self::get_days(NaiveDate::from(source))
    }

    fn date_type() -> SqlType {
        SqlType::Date
    }
}

impl DateConverter for u32 {
    fn to_date(&self, tz: Tz) -> ValueRef<'static> {
        ValueRef::DateTime(*self, tz)
    }

    fn get_stamp(source: Value) -> Self {
        DateTime::<Tz>::from(source).timestamp() as Self
    }

    fn date_type() -> SqlType {
        SqlType::DateTime(DateTimeType::DateTime32)
    }
}

impl DateConverter for i32 {
    fn to_date(&self, _tz: Tz) -> ValueRef<'static> {
        ValueRef::Date32(*self)
    }

    fn get_stamp(source: Value) -> Self {
        match source {
            Value::Date32(days) => days,
            Value::Date(days) => i32::from(days),
            other => date_days(NaiveDate::from(other)) as i32,
        }
    }

    fn date_type() -> SqlType {
        SqlType::Date32
    }
}

/// The days of `date` since 1970-01-01, negative before it.
pub(crate) fn date_days(date: NaiveDate) -> i64 {
    const UNIX_EPOCH_DAY: i64 = 719_163;
    i64::from(date.num_days_from_ce()) - UNIX_EPOCH_DAY
}

/// The date `days` after 1970-01-01, if chrono can hold it.
pub(crate) fn days_to_date(days: i64) -> Option<NaiveDate> {
    NaiveDate::from_ymd_opt(1970, 1, 1)?.checked_add_signed(chrono::Duration::try_days(days)?)
}