use url::Url;

use crate::providers::{build_proxy_url, strip_url_scheme};
use crate::videos::ServerOptions;

const DOODSTREAM_HOSTS: &[&str] = &[
    "doodstream.com",
    "turboplayers.xyz",
    "trailerhg.xyz",
    "streamhg.com",
];

const LULUSTREAM_HOSTS: &[&str] = &[
    "luluvdo.com",
    "lulustream.com",
];

const VIDARA_HOSTS: &[&str] = &[
    "vidara.so",
];

#[allow(dead_code)]
pub fn proxy_name_for_url(url: &str) -> Option<&'static str> {
    let parsed = match !url.starts_with("http://") && !url.starts_with("https://"){
        true => Url::parse(&format!("https://{}", url)).ok()?,
        false => Url::parse(url).ok()?
    };
    let host = parsed.host_str()?.to_ascii_lowercase();
    if DOODSTREAM_HOSTS.contains(&host.as_str()) {
        return Some("doodstream");
    }

    if LULUSTREAM_HOSTS.contains(&host.as_str()) {
        return Some("lulustream");
    }

    if VIDARA_HOSTS.contains(&host.as_str()) {
        return Some("vidara");
    }

    None
}

#[allow(dead_code)]
pub fn rewrite_hoster_url(options: &ServerOptions, url: &str) -> String {
    match proxy_name_for_url(url) {
        Some(proxy_name) => build_proxy_url(options, proxy_name, &strip_url_scheme(url)),
        None => url.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::{proxy_name_for_url, rewrite_hoster_url};
    use crate::videos::ServerOptions;

    fn options() -> ServerOptions {
        ServerOptions {
            client_version: None,
            featured: None,
            category: None,
            sites: None,
            filter: None,
            language: None,
            public_url_base: Some("https://example.com".to_string()),
            requester: None,
            network: None,
            stars: None,
            categories: None,
            duration: None,
            sort: None,
            sexuality: None,
        }
    }

    #[test]
    fn matches_doodstream_family_hosts() {
        assert_eq!(
            proxy_name_for_url("https://turboplayers.xyz/t/69bdfb21cc640"),
            Some("doodstream")
        );
        assert_eq!(
            proxy_name_for_url("https://trailerhg.xyz/e/ttdc7a6qpskt"),
            Some("doodstream")
        );
        assert_eq!(
            proxy_name_for_url("https://streamhg.com/about"),
            Some("doodstream")
        );
        assert_eq!(proxy_name_for_url("https://example.com/video"), None);
    }

    #[test]
    fn rewrites_known_hoster_urls_to_proxy_urls() {
        assert_eq!(
            rewrite_hoster_url(&options(), "https://turboplayers.xyz/t/69bdfb21cc640"),
            "https://example.com/proxy/doodstream/turboplayers.xyz/t/69bdfb21cc640"
        );
        assert_eq!(
            rewrite_hoster_url(&options(), "https://example.com/video"),
            "https://example.com/video"
        );
    }
}
