use crate::models::{FeedID, Url};
use crate::schema::fav_icons;
use chrono::{DateTime, Utc};

#[derive(Identifiable, Queryable, Clone, Debug, Insertable, Eq)]
#[diesel(primary_key(feed_id))]
#[diesel(table_name = fav_icons)]
#[diesel(check_for_backend(SQLite))]
pub struct FatFavIcon {
    pub feed_id: FeedID,
    #[diesel(column_name = "date")]
    pub expires: DateTime<Utc>,
    pub format: Option<String>,
    pub etag: Option<String>,
    pub lowres_source_url: Option<Url>,
    pub lowres: Option<Vec<u8>>,
    pub highres: Option<Vec<u8>>,
    pub highres_source_url: Option<Url>,
}

impl PartialEq for FatFavIcon {
    fn eq(&self, other: &FatFavIcon) -> bool {
        self.feed_id == other.feed_id
    }
}

impl From<FavIcon> for FatFavIcon {
    fn from(value: FavIcon) -> Self {
        FatFavIcon {
            feed_id: value.feed_id,
            expires: value.expires,
            format: value.format,
            etag: value.etag,
            lowres_source_url: value.source_url,
            lowres: value.data,
            highres: None,
            highres_source_url: None,
        }
    }
}

impl FatFavIcon {
    pub fn is_expired(&self) -> bool {
        Utc::now() >= self.expires
    }
}

#[derive(Identifiable, Queryable, Clone, Debug, Insertable, Eq)]
#[diesel(primary_key(feed_id))]
#[diesel(table_name = fav_icons)]
#[diesel(check_for_backend(SQLite))]
pub struct FavIcon {
    pub feed_id: FeedID,
    #[diesel(column_name = "date")]
    pub expires: DateTime<Utc>,
    pub format: Option<String>,
    pub etag: Option<String>,
    #[diesel(column_name = "lowres_source_url")]
    pub source_url: Option<Url>,
    #[diesel(column_name = "lowres")]
    pub data: Option<Vec<u8>>,
}

impl PartialEq for FavIcon {
    fn eq(&self, other: &FavIcon) -> bool {
        self.feed_id == other.feed_id
    }
}

impl From<FatFavIcon> for FavIcon {
    fn from(value: FatFavIcon) -> Self {
        FavIcon {
            feed_id: value.feed_id,
            expires: value.expires,
            format: value.format,
            etag: value.etag,
            source_url: value.lowres_source_url,
            data: value.lowres,
        }
    }
}

impl FavIcon {
    pub fn is_expired(&self) -> bool {
        Utc::now() >= self.expires
    }
}
