use chrono::NaiveDateTime;
use serde::Deserialize;
use std::cmp::{Ord, Ordering, PartialOrd};
use std::fs;

#[derive(Eq, PartialEq, Deserialize)]
pub struct Entry {
    pub title: String,
    pub tmdb_id: u64, // NB: ids can be non-unique for movie or show

    pub first_aired: Option<String>,
    pub released_utc_ms: Option<i64>,

    pub in_collection: Option<bool>,
    pub in_watchlist: Option<bool>,
    pub watched: Option<bool>,
    pub hidden: Option<bool>,
    pub favorite: Option<bool>,
}

impl Entry {
    pub fn from_file(file_path: &str) -> Result<Vec<Entry>, Box<dyn std::error::Error>> {
        let content = fs::read_to_string(file_path)?;
        let entries: Vec<Entry> = serde_json::from_str(&content)?;
        Ok(entries)
    }

    pub fn is_movie(&self) -> Option<bool> {
        match (self.first_aired.is_some(), self.released_utc_ms.is_some()) {
            (false, true) => Some(true),
            (true, false) => Some(false),
            (_, _) => None, // XXX: lacking heuristics
        }
    }

    pub fn is_favorite(&self) -> Option<bool> {
        if self.hidden.unwrap_or(false) {
            Some(false)
        } else if self.favorite.unwrap_or(false) || self.in_collection.unwrap_or(false) {
            Some(true)
        } else {
            None // in_watchlist || watched
        }
    }

    pub fn get_timestamp(&self) -> Option<i64> {
        if let Some(Some(t)) = self.released_utc_ms.map(|t| t.checked_div(1000)) {
            return Some(t);
        }
        if let Some(Some(t)) =
            self.first_aired.as_ref().map(|t| NaiveDateTime::parse_from_str(t, "%Y-%m-%dT%H:%M:%SZ").ok())
        {
            return Some(t.and_utc().timestamp());
        }
        None
    }
}

impl PartialOrd for Entry {
    fn partial_cmp(&self, other: &Entry) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Entry {
    fn cmp(&self, other: &Entry) -> Ordering {
        let ob = |v: Option<bool>| -> i8 {
            match v {
                Some(true) => -1, // ascending
                None => 0,
                Some(false) => 1,
            }
        };
        (ob(self.is_favorite()), &self.title, self.is_movie(), self.tmdb_id).cmp(&(
            ob(other.is_favorite()),
            &other.title,
            other.is_movie(),
            other.tmdb_id,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::DateTime;
    use tempfile::NamedTempFile;

    impl Entry {
        pub fn default() -> Self {
            Entry {
                title: "The Movie".to_string(),
                tmdb_id: 666,
                first_aired: None,
                released_utc_ms: None,
                in_collection: None,
                in_watchlist: None,
                watched: None,
                hidden: None,
                favorite: None,
            }
        }
    }

    fn test_parse(json: &str) -> Result<Vec<Entry>, Box<dyn std::error::Error>> {
        let temp_file = NamedTempFile::new().unwrap();
        fs::write(temp_file.path(), json).unwrap();
        Entry::from_file(temp_file.path().to_str().unwrap())
    }

    #[test]
    fn test_parse_json_file_err() {
        let result = Entry::from_file("/tmp/.nonexistent_file.json");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_json_empty() {
        let result = test_parse("[]");
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_parse_json() {
        let content = r#"
        [
            {"title": "Movie 1", "in_collection": true, "tmdb_id": 1},
            {"title": "Movie 2", "in_collection": false, "tmdb_id": 2},
            {"title": "Movie 3", "in_collection": true, "tmdb_id": 3}
        ]
        "#;
        let result = test_parse(content);
        assert_eq!(result.unwrap().len(), 3);
    }

    #[test]
    fn test_parse_json_syntax_err() {
        let content = r#"{ "invalid": "json" }"#;
        let result = test_parse(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_date() {
        let mut entry = Entry::default();
        assert!(entry.get_timestamp().is_none());
        entry.first_aired =
            Some(DateTime::from_timestamp_secs(1671510369).unwrap().format("%Y-%m-%dT%H:%M:%SZ").to_string());
        assert_eq!(entry.get_timestamp().unwrap_or(0), 1671510369);
        entry.released_utc_ms = Some(1425510000000);
        assert_eq!(entry.get_timestamp().unwrap_or(0), 1425510000);
    }

    #[test]
    fn test_sort() {
        fn make_entries<F>(f: F) -> Vec<Entry>
        where
            F: Fn(Entry, Entry) -> (Entry, Entry),
        {
            let mut a = Entry::default();
            let mut b = Entry::default();
            (a, b) = f(a, b);
            let mut v = vec![a, b];
            v.sort();
            v
        }

        let v = make_entries(|mut a, mut b| {
            a.title = "B".to_string();
            b.title = "A".to_string();
            (a, b)
        });
        assert_eq!(v.get(0).unwrap().title, "A");
        assert_eq!(v.get(1).unwrap().title, "B");

        let v = make_entries(|mut a, mut b| {
            a.favorite = Some(false);
            b.favorite = Some(true);
            (a, b)
        });
        assert_eq!(v.get(0).unwrap().favorite, Some(true));
        assert_eq!(v.get(1).unwrap().favorite, Some(false));

        let v = make_entries(|mut a, mut b| {
            a.favorite = None;
            b.favorite = Some(true);
            (a, b)
        });
        assert_eq!(v.get(0).unwrap().favorite, Some(true));
        assert_eq!(v.get(1).unwrap().favorite, None);

        let v = make_entries(|mut a, mut b| {
            b.favorite = Some(false);
            a.favorite = None;
            (a, b)
        });
        assert_eq!(v.get(0).unwrap().favorite, None);
        assert_eq!(v.get(1).unwrap().favorite, Some(false));
    }
}