use bytes::Bytes;
use log::{debug, warn};
use regex::RegexBuilder;
use serde::Deserialize;
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::PathBuf;

#[derive(Debug, Copy, Clone, clap::ValueEnum)]
pub enum ShowType {
    Movie,
    Show,
}

impl ShowType {
    pub fn from_is_movie(is_movie: Option<bool>) -> Self {
        if is_movie.unwrap_or(true) { ShowType::Movie } else { ShowType::Show }
    }

    pub fn as_api_path(&self) -> &str {
        match self {
            ShowType::Movie => "movie",
            ShowType::Show => "tv",
        }
    }
}

pub struct ShowHandle {
    pub tmdb_id: u64,
    pub show_type: ShowType,
}

pub struct HttpClient {
    client: reqwest::blocking::Client,
    headers: reqwest::header::HeaderMap,
    params: Vec<(String, String)>,
}

impl HttpClient {
    pub fn new() -> Self {
        Self {
            client: reqwest::blocking::Client::new(),
            headers: reqwest::header::HeaderMap::new(),
            params: Vec::new(),
        }
    }

    pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
        for (k, v) in headers
            .into_iter()
            .map(|(k, v)| (reqwest::header::HeaderName::try_from(k), reqwest::header::HeaderValue::try_from(v)))
            .filter(|(k, v)| k.is_ok() && v.is_ok())
        {
            // XXX: alternatively just every time or https://github.com/seanmonstar/reqwest/issues/555
            self.headers.try_insert(k.unwrap(), v.unwrap()).ok();
        }
        self
    }

    pub fn with_query(mut self, params: &[(&str, &str)]) -> Self {
        for (k, v) in params {
            self.params.push((k.to_string(), v.to_string()));
        }
        self
    }

    pub fn get_json(&self, url: &str) -> Option<Bytes> {
        // TODO: response.json() or with lifetime: get_json<'de, T>(&self, url: &str) -> Option<T> where T: Deserialize<'de>
        self.get(url, r"^application/json( *; *charset *= *utf-8)?$")
    }

    pub fn get_image(&self, url: &str) -> Option<Bytes> {
        // TODO: check extension/content-type for any image type, or return it
        self.get(url, r"^image/jpe?g$")
    }

    fn get(&self, url: &str, expect_ct: &str) -> Option<Bytes> {
        match self.get_internal(url, expect_ct) {
            Err(e) => {
                warn!("Cannot fetch '{}': {}", url, e);
                None
            }
            Ok(r) => Some(r),
        }
    }

    fn get_internal(&self, url: &str, expect_ct: &str) -> Result<Bytes, Box<dyn Error>> {
        debug!("Requesting '{}'", url);

        let re = RegexBuilder::new(expect_ct).case_insensitive(true).build().unwrap(); // TODO: also static/lazy
        let response = self.client.get(url).query(&self.params).headers(self.headers.clone()).send()?;
        let content_type = response.headers().get("Content-Type").and_then(|v| v.to_str().ok()).unwrap_or("");

        match (response.status().as_u16(), re.is_match(content_type)) {
            (200, true) => Ok(response.bytes()?),
            (200, _) => Err(format!("Content-Type '{}'", content_type))?,
            (status, _) => Err(format!("Response status {}", status))?,
        }
    }
}

#[derive(Deserialize)]
struct ApiResponse {
    // id: i64,
    // title: String,
    poster_path: String,
}

pub struct CoverClient {
    client: HttpClient,
    api_base_url: String,
    img_base_url: String,
}

impl CoverClient {
    pub fn new(client: HttpClient, api_base_url: String, img_base_url: String, api_key: String) -> Self {
        Self {
            client: client
                .with_headers(
                    [
                        ("Authorization".to_string(), format!("Bearer {}", api_key)),
                        ("User-Agent".to_string(), "Mozilla/5.0 (compatible; SeriesGuideExport)".to_string()),
                    ]
                    .into(),
                )
                .with_query(&[("api_key", &api_key)]),
            api_base_url: api_base_url.trim_end_matches("/").to_string(),
            img_base_url: img_base_url.trim_end_matches("/").to_string(),
        }
    }

    pub fn get_cover_image(&self, handle: &ShowHandle) -> Option<Bytes> {
        match self.get_cover_url(handle) {
            None => None,
            Some(url) => self.client.get_image(&url),
        }
    }

    fn get_cover_url(&self, handle: &ShowHandle) -> Option<String> {
        // TODO: move ownership from parsed buffer into the JSON object
        match self.client.get_json(&self.make_api_url(handle)) {
            None => None,
            Some(response) => match serde_json::from_slice::<ApiResponse>(&response) {
                Err(_) => None,
                Ok(api) => Some(self.make_img_url(&api.poster_path)), // TODO: if match regex
            },
        }
    }

    fn make_api_url(&self, handle: &ShowHandle) -> String {
        format!("{}/3/{}/{}", self.api_base_url, handle.show_type.as_api_path(), handle.tmdb_id)
    }

    fn make_img_url(&self, poster_path: &str) -> String {
        // TODO: /configuration API call, https://developer.themoviedb.org/docs/image-basics
        format!("{}/t/p/w342{}", self.img_base_url, poster_path)
    }
}

pub struct CoverCache {
    client: CoverClient, // NB: composition over inheritance, so traits or here wrappers/proxies instead
    base_path: PathBuf,
    base_url: String,
}

impl CoverCache {
    pub fn for_tmdb(base_path: &str, api_key: &str) -> Self {
        Self {
            client: CoverClient::new(
                HttpClient::new(),
                "https://api.themoviedb.org".to_string(),
                "https://image.tmdb.org".to_string(),
                api_key.to_string(), // https://github.com/rickylawson/freekeys/blob/master/index.js
            ),
            base_path: base_path.into(), // TODO: check or create cache dir
            base_url: "https://www.themoviedb.org".to_string(),
        }
    }

    pub fn get(&self, handle: &ShowHandle) -> Option<Bytes> {
        if let Some(result) = self.get_cache(handle) {
            return if result.is_empty() { None } else { Some(result) };
        }

        let result = self.client.get_cover_image(handle);
        self.set_cache(handle, result.as_ref()); // including None
        result
    }

    pub fn get_link(&self, handle: &ShowHandle) -> String {
        format!("{}/{}/{}", self.base_url, handle.show_type.as_api_path(), handle.tmdb_id)
    }

    fn make_path(&self, handle: &ShowHandle) -> PathBuf {
        // TODO: would need to encode/remember extension
        self.base_path.join(format!("{}-{}.jpg", handle.tmdb_id, handle.show_type.as_api_path()))
    }

    fn get_cache(&self, handle: &ShowHandle) -> Option<Bytes> {
        fs::read(self.make_path(handle)).ok().map(Bytes::from)
    }

    fn set_cache(&self, handle: &ShowHandle, data: Option<&Bytes>) {
        let buf: &[u8] = data.map_or(&[], |b| b.as_ref()); // XXX: explicit type due to [u8;0] vs [u8;_]
        if let Err(e) = fs::write(self.make_path(handle), buf) {
            warn!("Cannot write to cache for {}: {}", handle.tmdb_id, e);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use httpmock::MockServer;
    use tempfile::TempDir;

    impl CoverCache {
        fn new(client: CoverClient, base_path: String, base_url: String) -> Self {
            Self { client, base_path: base_path.into(), base_url }
        }
    }

    #[test]
    fn test_http_get() {
        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method("GET").path("/foo").query_param("bar", "baz").header("User-Agent", "UA");
            then.status(200).header("Content-Type", "application/json").body("{}");
        });
        let client = HttpClient::new().with_headers([("User-Agent".to_string(), "UA".to_string())].into());

        let response = client.get_json(&server.url("/foo?bar=baz")); // 200
        assert_eq!(response.unwrap(), "{}");

        let response = client.get_json(&server.url("/xxx")); // 404
        assert!(response.is_none());

        let response = client.get_json("http://127.0.0.1:0/xxx"); // OSERROR
        assert!(response.is_none());

        assert_eq!(mock.calls(), 1);
    }

    #[test]
    fn test_cover_get() {
        let server = MockServer::start();
        let api_mock = server.mock(|when, then| {
            when.method("GET").path("/3/movie/42").header_exists("Authorization");
            then.status(200).header("Content-Type", "application/json").body(r#"{"poster_path": "/foo.jpg"}"#);
        });
        let image_mock = server.mock(|when, then| {
            when.method("GET").path("/t/p/w342/foo.jpg").header_exists("Authorization");
            then.status(200).header("Content-Type", "image/jpeg").body(b"JPEG");
        });
        let client = CoverClient::new(HttpClient::new(), server.base_url(), server.base_url(), "1234".to_string());

        let response = client.get_cover_url(&ShowHandle { tmdb_id: 42, show_type: ShowType::Movie });
        assert_eq!(response.unwrap(), format!("{}/t/p/w342/foo.jpg", server.base_url()));

        let response = client.get_cover_image(&ShowHandle { tmdb_id: 42, show_type: ShowType::Movie });
        assert_eq!(response.unwrap().as_ref(), b"JPEG");

        assert_eq!(api_mock.calls(), 2);
        assert_eq!(image_mock.calls(), 1);
    }

    #[test]
    fn test_cover_cache() {
        let server = MockServer::start();
        let api_mock = server.mock(|when, then| {
            when.method("GET").path("/3/movie/42").header_exists("Authorization").query_param_exists("api_key");
            then.status(200).header("Content-Type", "application/json").body(r#"{"poster_path": "/foo.jpg"}"#);
        });
        let image_mock = server.mock(|when, then| {
            when.method("GET").path("/t/p/w342/foo.jpg").header_exists("Authorization");
            then.status(200).header("Content-Type", "image/jpeg").body(b"JPEG");
        });
        let cache = TempDir::new().unwrap();
        let cache_dir = cache.path().canonicalize().unwrap().into_string().unwrap();
        let client = CoverClient::new(HttpClient::new(), server.base_url(), server.base_url(), "1234".to_string());
        let client = CoverCache::new(client, cache_dir, server.base_url());

        let response = client.get(&ShowHandle { tmdb_id: 666, show_type: ShowType::Movie });
        assert!(response.is_none());

        let response = client.get(&ShowHandle { tmdb_id: 42, show_type: ShowType::Show });
        assert!(response.is_none());
        assert!(fs::exists(cache.path().join("42-tv.jpg")).unwrap());
        assert!(fs::metadata(cache.path().join("42-tv.jpg")).unwrap().len() == 0);

        let response = client.get(&ShowHandle { tmdb_id: 42, show_type: ShowType::Movie });
        assert_eq!(response.unwrap().as_ref(), b"JPEG");
        assert!(fs::exists(cache.path().join("42-movie.jpg")).unwrap());

        let response = client.get(&ShowHandle { tmdb_id: 42, show_type: ShowType::Movie });
        assert_eq!(response.unwrap().as_ref(), b"JPEG");

        let url = client.get_link(&ShowHandle { tmdb_id: 42, show_type: ShowType::Movie });
        assert_eq!(url, server.url("/movie/42"));

        assert_eq!(api_mock.calls(), 1);
        assert_eq!(image_mock.calls(), 1);
    }

    #[test]
    fn test_tmdb_cache() {
        let client = CoverCache::for_tmdb("/tmp/cache", "secret");
        assert_eq!(client.base_path.to_str().unwrap(), "/tmp/cache");
        assert_eq!(client.base_url, "https://www.themoviedb.org");
        assert_eq!(client.client.api_base_url, "https://api.themoviedb.org");
        assert_eq!(client.client.img_base_url, "https://image.tmdb.org");
        assert_eq!(client.client.client.headers.get("Authorization").unwrap(), "Bearer secret");
        assert_eq!(client.client.client.params.get(0).unwrap(), &("api_key".to_string(), "secret".to_string()));
    }
}