use crate::DbPool;
use crate::api::ClientVersion;
use crate::providers::Provider;
use crate::status::*;
use crate::util::cache::VideoCache;
use crate::util::parse_abbreviated_number;
use crate::util::time::parse_time_to_seconds;
use crate::videos::{ServerOptions, VideoFormat, VideoItem};

use async_trait::async_trait;
use error_chain::error_chain;
use htmlentity::entity::{ICodedDataTrait, decode};
use std::vec;
use titlecase::Titlecase;
use wreq::Version;

error_chain! {
    foreign_links {
        Io(std::io::Error);
        HttpRequest(wreq::Error);
    }
    errors {
        Parse(msg: String)
    }
}

#[derive(Debug, Clone)]
pub struct NoodlemagazineProvider {
    url: String,
}

impl NoodlemagazineProvider {
    pub fn new() -> Self {
        Self {
            url: "https://noodlemagazine.com".to_string(),
        }
    }

    fn build_channel(&self, _clientversion: ClientVersion) -> Channel {
        Channel {
            id: "noodlemagazine".into(),
            name: "Noodlemagazine".into(),
            description: "The Best Search Engine of HD Videos".into(),
            premium: false,
            favicon: "https://www.google.com/s2/favicons?sz=64&domain=noodlemagazine.com".into(),
            status: "active".into(),
            categories: vec![],
            options: vec![],
            nsfw: true,
            cacheDuration: Some(1800),
        }
    }

    async fn get(
        &self,
        cache: VideoCache,
        page: u8,
        _sort: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let video_url = format!(
            "{}/popular/recent?sort_by=views&sort_order=desc&p={}",
            self.url,
            page.saturating_sub(1)
        );

        let old_items = match cache.get(&video_url) {
            Some((t, i)) if t.elapsed().unwrap_or_default().as_secs() < 300 => return Ok(i.clone()),
            Some((_, i)) => i.clone(),
            None => vec![],
        };

        let mut requester = match options.requester.clone() {
            Some(r) => r,
            None => return Ok(old_items),
        };

        let text = requester
            .get(&video_url, Some(Version::HTTP_2))
            .await
            .unwrap_or_default();

        let items = self.get_video_items_from_html(text);

        if items.is_empty() {
            Ok(old_items)
        } else {
            cache.remove(&video_url);
            cache.insert(video_url, items.clone());
            Ok(items)
        }
    }

    async fn query(
        &self,
        cache: VideoCache,
        page: u8,
        query: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let q = query.trim().replace(' ', "%20");
        let video_url = format!("{}/video/{}?p={}", self.url, q, page.saturating_sub(1));

        let old_items = match cache.get(&video_url) {
            Some((t, i)) if t.elapsed().unwrap_or_default().as_secs() < 300 => return Ok(i.clone()),
            Some((_, i)) => i.clone(),
            None => vec![],
        };

        let mut requester = match options.requester.clone() {
            Some(r) => r,
            None => return Ok(old_items),
        };

        let text = requester
            .get(&video_url, Some(Version::HTTP_2))
            .await
            .unwrap_or_default();

        let items = self.get_video_items_from_html(text);

        if items.is_empty() {
            Ok(old_items)
        } else {
            cache.remove(&video_url);
            cache.insert(video_url, items.clone());
            Ok(items)
        }
    }

    fn get_video_items_from_html(&self, html: String) -> Vec<VideoItem> {
        if html.is_empty() || html.contains("404 Not Found") {
            return vec![];
        }

        let section = match html.split(">Show more</div>").next() {
            Some(s) => s,
            None => return vec![],
        };

        let list = match section
            .split("<div class=\"list_videos\" id=\"list_videos\">")
            .nth(1)
        {
            Some(l) => l,
            None => return vec![],
        };

        list.split("<div class=\"item\">")
            .skip(1)
            .filter_map(|segment| self.get_video_item(segment.to_string()).ok())
            .collect()
    }

    fn proxy_url(&self, video_url: &str) -> String {
        let target = video_url
            .strip_prefix("https://")
            .or_else(|| video_url.strip_prefix("http://"))
            .unwrap_or(video_url)
            .trim_start_matches('/');

        format!("https://hottub.spacemoehre.de/proxy/noodlemagazine/{target}")
    }

    fn get_video_item(&self, video_segment: String) -> Result<VideoItem> {
        let href = video_segment
            .split("<a href=\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .ok_or_else(|| Error::from("missing href"))?;

        let video_url = format!("{}{}", self.url, href);

        let mut title = video_segment
            .split("<div class=\"title\">")
            .nth(1)
            .and_then(|s| s.split('<').next())
            .unwrap_or("")
            .trim()
            .to_string();

        title = decode(title.as_bytes())
            .to_string()
            .unwrap_or(title)
            .titlecase();

        let id = video_url
            .split('/')
            .nth(4)
            .and_then(|s| s.split('.').next())
            .ok_or_else(|| Error::from("missing id"))?
            .to_string();

        let thumb = video_segment
            .split("data-src=\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .unwrap_or("")
            .to_string();

        let raw_duration = video_segment
            .split("#clock-o\"></use></svg>")
            .nth(1)
            .and_then(|s| s.split('<').next())
            .unwrap_or("0:00");

        let duration = parse_time_to_seconds(raw_duration).unwrap_or(0) as u32;

        let views = video_segment
            .split("#eye\"></use></svg>")
            .nth(1)
            .and_then(|s| s.split('<').next())
            .and_then(|v| parse_abbreviated_number(v.trim()))
            .unwrap_or(0);
        let proxy_url = self.proxy_url(&video_url);

        Ok(VideoItem::new(
            id,
            title,
            proxy_url.clone(),
            "noodlemagazine".into(),
            thumb,
            duration,
        )
        .views(views)
        .formats(vec![
            VideoFormat::new(proxy_url, "auto".into(), "video/mp4".into())
                .format_id("auto".into())
                .format_note("proxied".into()),
        ]))
    }
}

#[async_trait]
impl Provider for NoodlemagazineProvider {
    async fn get_videos(
        &self,
        cache: VideoCache,
        pool: DbPool,
        sort: String,
        query: Option<String>,
        page: String,
        per_page: String,
        options: ServerOptions,
    ) -> Vec<VideoItem> {
        let _ = pool;
        let _ = per_page;

        let page = page.parse::<u8>().unwrap_or(1);

        let res = match query {
            Some(q) => self.query(cache, page, &q, options).await,
            None => self.get(cache, page, &sort, options).await,
        };

        res.unwrap_or_else(|e| {
            eprintln!("Noodlemagazine error: {e}");
            vec![]
        })
    }

    fn get_channel(&self, clientversion: ClientVersion) -> Option<Channel> {
        Some(self.build_channel(clientversion))
    }
}

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

    #[test]
    fn rewrites_video_pages_to_hottub_proxy() {
        let provider = NoodlemagazineProvider::new();

        assert_eq!(
            provider.proxy_url("https://noodlemagazine.com/watch/-123_456"),
            "https://hottub.spacemoehre.de/proxy/noodlemagazine/noodlemagazine.com/watch/-123_456"
        );
    }

    #[test]
    fn parses_listing_without_detail_page_requests() {
        let provider = NoodlemagazineProvider::new();
        let html = r#"
            <div class="list_videos" id="list_videos">
                <div class="item">
                    <a href="/watch/-123_456">
                        <img data-src="https://thumb.example/test.jpg" />
                    </a>
                    <div class="title">sample &amp; title</div>
                    <svg><use></use></svg>#clock-o"></use></svg>12:34<
                    <svg><use></use></svg>#eye"></use></svg>1.2K<
                </div>
            >Show more</div>
        "#;

        let items = provider.get_video_items_from_html(html.to_string());

        assert_eq!(items.len(), 1);
        assert_eq!(
            items[0].url,
            "https://hottub.spacemoehre.de/proxy/noodlemagazine/noodlemagazine.com/watch/-123_456"
        );
        assert_eq!(items[0].formats.as_ref().map(|f| f.len()), Some(1));
    }
}
