use chrono::NaiveDate;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Sub;

const READABLE_DATE_FORMAT: &'static str = "%b %-e, %Y";

/// ReadableDate wraps a date and could be (de)serialize with format like
/// `Apr 4, 2010`.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ReadableDate(NaiveDate);

impl ReadableDate {
    pub fn new(year: i32, month: u32, day: u32) -> Self {
        Self(NaiveDate::from_ymd(year, month, day))
    }

    /// Create a `ReadableDate` for today.
    pub fn today() -> Self {
        Self(chrono::Local::today().naive_local())
    }
}

impl Default for ReadableDate {
    fn default() -> Self {
        Self::today()
    }
}

impl fmt::Display for ReadableDate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Serialize for ReadableDate {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&format!("{}", self.0.format(READABLE_DATE_FORMAT)))
    }
}

impl<'de> Deserialize<'de> for ReadableDate {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self(
            NaiveDate::parse_from_str(&s, READABLE_DATE_FORMAT)
                .map_err(serde::de::Error::custom)?,
        ))
    }
}

macro_rules! impl_sub {
    ($for:ty, $rhs:ty) => {
        impl Sub for $for {
            type Output = chrono::Duration;

            fn sub(self, other: $rhs) -> Self::Output {
                self.0 - other.0
            }
        }
    };
}

impl_sub! { ReadableDate, ReadableDate }
impl_sub! { &ReadableDate, &ReadableDate }

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

    #[test]
    fn date_sub() {
        assert_eq!(
            ReadableDate::new(2020, 02, 02) - ReadableDate::new(2020, 02, 01),
            chrono::Duration::days(1)
        );
    }
}
