use crate::cover_client::{CoverCache, ShowHandle, ShowType};
use crate::entry::Entry;
use crate::html_export::PageExport;
use clap::Parser;
use env_logger::Env;
use log::{debug, error, info};

mod cover_client;
mod entry;
mod html_export;

#[derive(Debug, Copy, Clone, PartialEq, clap::ValueEnum)]
pub enum Flag {
    // cannot have Option<bool> or negative flags: https://github.com/clap-rs/clap/issues/1649
    True = 1,
    False = 0,
}

#[derive(Parser, Debug)]
struct Cli {
    /// List of .json files to process
    file_path: Vec<String>,

    /// Cover image cache directory
    #[arg(short)]
    cache_dir: String,

    /// TMDB API key
    #[arg(short)]
    api_key: String,

    /// HTML output
    #[arg(short)]
    out_file: String,

    /// Whether checks should be treated as OR instead of AND
    #[arg(long, action)]
    is_check_or: bool,

    #[arg(long)]
    is_in_collection: Option<Flag>,
    #[arg(long)]
    is_in_watchlist: Option<Flag>,
    #[arg(long)]
    is_watched: Option<Flag>,
    #[arg(long)]
    is_hidden: Option<Flag>,
    #[arg(long)]
    is_favorite: Option<Flag>,
}

fn main() {
    env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();

    let cli = Cli::parse();
    match run(&cli) {
        Ok((total, count)) => {
            info!("Processed {} of {} entries", count, total)
        }
        Err(e) => {
            error!("Error: {}", e);
            std::process::exit(1);
        }
    }
}

fn match_entry(cli: &Cli, entry: &Entry, conjunction: bool) -> bool {
    [
        (cli.is_in_collection, entry.in_collection),
        (cli.is_in_watchlist, entry.in_watchlist),
        (cli.is_watched, entry.watched),
        (cli.is_hidden, entry.hidden),
        (cli.is_favorite, entry.favorite),
    ]
    .iter()
    .filter(|(c, _)| c.is_some()) // only evaluate where cli match given
    .map(|(c, e)| (c.unwrap_or(Flag::False) == Flag::True, e.unwrap_or(false))) // coalesce to bool
    .fold(conjunction, |a, (c, e)| if conjunction { a && c == e } else { a || c == e })
}

fn run(cli: &Cli) -> Result<(usize, usize), Box<dyn std::error::Error>> {
    let mut entries: Vec<Entry> = vec![];
    for file_path in &cli.file_path {
        entries.extend(Entry::from_file(file_path)?);
    }
    entries.sort();

    let covers = CoverCache::for_tmdb(&cli.cache_dir, &cli.api_key);
    let mut html = PageExport::new();

    let total = entries.len();
    let mut count = 0;
    for entry in entries.into_iter().filter(|e| match_entry(cli, e, !cli.is_check_or)) {
        let handle = ShowHandle { tmdb_id: entry.tmdb_id, show_type: ShowType::from_is_movie(entry.is_movie()) };
        let cover = covers.get(&handle);
        debug!("Title: {}", entry.title);
        html.add(
            &entry.title,
            covers.get_link(&handle),
            &entry.is_favorite(),
            &entry.is_movie(),
            &entry.get_timestamp(),
            cover.as_ref().map(|b| b.as_ref()),
        );
        count += 1;
    }
    html.write(&cli.out_file);

    Ok((total, count))
}

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

    impl Cli {
        fn default() -> Self {
            Cli {
                file_path: vec!["./sample.json".to_string()],
                cache_dir: "/tmp/".to_string(),
                api_key: "s3cr3t".to_string(),
                out_file: "/dev/null".to_string(),
                is_check_or: false,
                is_in_collection: None,
                is_in_watchlist: None,
                is_watched: None,
                is_hidden: None,
                is_favorite: None,
            }
        }
    }

    #[test]
    fn test_match() {
        let mut cli = Cli::default();
        let mut entry = Entry::default();
        assert!(match_entry(&cli, &entry, true)); // default true
        assert!(!match_entry(&cli, &entry, false)); // default false, match needed

        for (a, b, result_and, result_or) in [
            (Some(Flag::True), Some(true), true, true),
            (Some(Flag::False), Some(false), true, true),
            (None, Some(true), true, false),
            (None, Some(false), true, false),
            (None, None, true, false),
            (Some(Flag::True), None, false, false),
            (Some(Flag::True), Some(false), false, false),
            (Some(Flag::False), Some(true), false, false),
        ] {
            cli.is_favorite = a;
            entry.favorite = b;
            assert_eq!(match_entry(&cli, &entry, true), result_and);
            assert_eq!(match_entry(&cli, &entry, false), result_or);
        }
    }
}