use std::hash::{Hash, Hasher};

use super::{ArticleID, Url};
use crate::schema::images;

#[derive(Identifiable, Clone, Insertable, Queryable, Eq, Debug)]
#[diesel(primary_key(image_url))]
#[diesel(table_name = images)]
#[diesel(check_for_backend(SQLite))]
pub struct ImageMetadata {
    pub image_url: Url,
    pub article_id: ArticleID,
    pub file_path: String,
    pub width: Option<i32>,
    pub height: Option<i32>,
}

impl Hash for ImageMetadata {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.image_url.hash(state);
    }
}

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

#[derive(Clone, Eq, Debug)]
pub struct Image {
    pub image_url: Url,
    pub article_id: ArticleID,
    pub file_path: String,
    pub width: Option<i32>,
    pub height: Option<i32>,
    pub data: Vec<u8>,
}

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

impl Image {
    pub fn from_metadata(image: ImageMetadata, data: Vec<u8>) -> Self {
        Self {
            image_url: image.image_url,
            article_id: image.article_id,
            file_path: image.file_path,
            width: image.width,
            height: image.height,
            data,
        }
    }
}
