use crate::DbPool;
use crate::api::ClientVersion;
use crate::providers::{Provider, report_provider_error};
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, VideoItem};
use async_trait::async_trait;
use error_chain::error_chain;
use htmlentity::entity::{ICodedDataTrait, decode};
use serde_json::Value;
use std::vec;

pub const CHANNEL_METADATA: crate::providers::ProviderChannelMetadata =
    crate::providers::ProviderChannelMetadata {
        group_id: "mainstream-tube",
        tags: &["mainstream", "legacy", "general"],
    };

error_chain! {
    foreign_links {
        Io(std::io::Error);
        HttpRequest(wreq::Error);
    }
}

#[derive(Debug, Clone)]
pub struct RedtubeProvider {
    url: String,
}
impl RedtubeProvider {
    pub fn new() -> Self {
        RedtubeProvider {
            url: "https://www.redtube.com".to_string(),
        }
    }

    fn build_channel(&self, _clientversion: ClientVersion) -> Channel {
        Channel {
            id: "redtube".to_string(),
            name: "Redtube".to_string(),
            description: "Redtube brings you NEW porn videos every day for free".to_string(),
            premium: false,
            favicon: "https://www.google.com/s2/favicons?sz=64&domain=www.redtube.com".to_string(),
            status: "active".to_string(),
            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 _ = sort;
        let video_url = format!("{}/mostviewed?page={}", self.url, page);
        let old_items = match cache.get(&video_url) {
            Some((time, items)) => {
                if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 {
                    return Ok(items.clone());
                } else {
                    items.clone()
                }
            }
            None => {
                vec![]
            }
        };
        let mut requester =
            crate::providers::requester_or_default(&options, module_path!(), "missing_requester");
        let text = match requester.get(&video_url, None).await {
            Ok(text) => text,
            Err(e) => {
                report_provider_error(
                    "redtube",
                    "get.request",
                    &format!("url={video_url}; error={e}"),
                )
                .await;
                return Ok(old_items);
            }
        };
        let video_items: Vec<VideoItem> = self.get_video_items_from_html(text.clone());
        if !video_items.is_empty() {
            cache.remove(&video_url);
            cache.insert(video_url.clone(), video_items.clone());
        } else {
            return Ok(old_items);
        }
        Ok(video_items)
    }
    async fn query(
        &self,
        cache: VideoCache,
        page: u8,
        query: &str,
        sort: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let _ = sort; //TODO
        let search_string = query.to_lowercase().trim().replace(" ", "+");
        let video_url = format!("{}/?search={}&page={}", self.url, search_string, page);

        // Check our Video Cache. If the result is younger than 1 hour, we return it.
        let old_items = match cache.get(&video_url) {
            Some((time, items)) => {
                if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 {
                    return Ok(items.clone());
                } else {
                    let _ = cache.check().await;
                    return Ok(items.clone());
                }
            }
            None => {
                vec![]
            }
        };
        let mut requester =
            crate::providers::requester_or_default(&options, module_path!(), "missing_requester");
        let text = match requester.get(&video_url, None).await {
            Ok(text) => text,
            Err(e) => {
                report_provider_error(
                    "redtube",
                    "query.request",
                    &format!("url={video_url}; error={e}"),
                )
                .await;
                return Ok(old_items);
            }
        };
        let video_items: Vec<VideoItem> = self.get_video_items_from_html_query(text.clone());
        if !video_items.is_empty() {
            cache.remove(&video_url);
            cache.insert(video_url.clone(), video_items.clone());
        } else {
            return Ok(old_items);
        }
        Ok(video_items)
    }

    fn get_video_items_from_html(&self, html: String) -> Vec<VideoItem> {
        if html.is_empty() {
            println!("HTML is empty");
            return vec![];
        }
        let mut items: Vec<VideoItem> = Vec::new();
        let video_listing_content = html
            .split("<script type=\"application/ld+json\">")
            .collect::<Vec<&str>>()
            .get(1)
            .copied()
            .unwrap_or_default()
            .split("</script>")
            .collect::<Vec<&str>>()
            .get(0)
            .copied()
            .unwrap_or_default();
        let mut videos: Value = match serde_json::from_str(video_listing_content) {
            Ok(videos) => videos,
            Err(e) => {
                crate::providers::report_provider_error_background(
                    "redtube",
                    "get_video_items_from_html.json_parse",
                    &e.to_string(),
                );
                return items;
            }
        };
        let Some(video_list) = videos.as_array_mut() else {
            crate::providers::report_provider_error_background(
                "redtube",
                "get_video_items_from_html.json_not_array",
                "expected array",
            );
            return items;
        };
        for vid in video_list {
            let video_url: String = vid["embedUrl"].as_str().unwrap_or("").to_string();
            let mut title: String = vid["name"].as_str().unwrap_or("").to_string();
            // html decode
            title = decode(title.as_bytes()).to_string().unwrap_or(title);
            let id = video_url
                .split("=")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .to_string();
            let raw_duration = vid["duration"].as_str().unwrap_or("0");
            let duration = raw_duration
                .replace("PT", "")
                .replace("S", "")
                .parse::<u32>()
                .unwrap_or(0);
            let views: u64 = vid["interactionCount"].as_u64().unwrap_or(0);
            let thumb = vid["thumbnailUrl"].as_str().unwrap_or("").to_string();

            let video_item = VideoItem::new(
                id,
                title,
                video_url.to_string(),
                "redtube".to_string(),
                thumb,
                duration,
            )
            .views(views as u32);
            items.push(video_item);
        }
        return items;
    }

    fn get_video_items_from_html_query(&self, html: String) -> Vec<VideoItem> {
        if html.is_empty() {
            println!("HTML is empty");
            return vec![];
        }
        let mut items: Vec<VideoItem> = Vec::new();
        let video_listing_content = html
            .split("videos_grid")
            .collect::<Vec<&str>>()
            .get(1)
            .copied()
            .unwrap_or_default();
        let videos = video_listing_content
            .split("<li id=\"tags_videos_")
            .collect::<Vec<&str>>()[1..]
            .to_vec();
        for vid in videos {
            // for (i, c) in vid.split("\n").enumerate() {
            //     println!("{}: {}", i, c);
            // }
            let id = vid
                .split("data-video-id=\"")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split("\"")
                .collect::<Vec<&str>>()
                .get(0)
                .copied()
                .unwrap_or_default()
                .to_string();
            let video_url = format!("{}/{}", self.url, id);
            let title = vid
                .split(" <a title=\"")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split("\"")
                .collect::<Vec<&str>>()
                .get(0)
                .copied()
                .unwrap_or_default()
                .trim()
                .to_string();
            let thumb = vid
                .split("<img")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split(" data-src=\"")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split("\"")
                .collect::<Vec<&str>>()
                .get(0)
                .copied()
                .unwrap_or_default()
                .to_string();
            let raw_duration = vid
                .split("<span class=\"video-properties tm_video_duration\">")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split("</span>")
                .collect::<Vec<&str>>()
                .get(0)
                .copied()
                .unwrap_or_default()
                .trim()
                .to_string();
            let duration = parse_time_to_seconds(&raw_duration).unwrap_or(0) as u32;
            let views_str = vid
                .split("<span class='info-views'>")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split("</span>")
                .collect::<Vec<&str>>()
                .get(0)
                .copied()
                .unwrap_or_default()
                .trim()
                .to_string();
            let views = parse_abbreviated_number(&views_str).unwrap_or(0) as u32;
            let preview = vid
                .split("<img")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split(" data-mediabook=\"")
                .collect::<Vec<&str>>()
                .get(1)
                .copied()
                .unwrap_or_default()
                .split("\"")
                .collect::<Vec<&str>>()
                .get(0)
                .copied()
                .unwrap_or_default()
                .to_string();

            let video_item =
                VideoItem::new(id, title, video_url, "redtube".to_string(), thumb, duration)
                    .views(views)
                    .preview(preview);
            items.push(video_item);
        }
        return items;
    }
}

#[async_trait]
impl Provider for RedtubeProvider {
    async fn get_videos(
        &self,
        cache: VideoCache,
        pool: DbPool,
        sort: String,
        query: Option<String>,
        page: String,
        per_page: String,
        options: ServerOptions,
    ) -> Vec<VideoItem> {
        let _ = options;
        let _ = per_page;
        let _ = pool;
        let mut sort = sort.to_lowercase();
        if sort.contains("date") {
            sort = "mr".to_string();
        }
        let videos: std::result::Result<Vec<VideoItem>, Error> = match query {
            Some(q) => {
                self.query(cache, page.parse::<u8>().unwrap_or(1), &q, &sort, options)
                    .await
            }
            None => {
                self.get(cache, page.parse::<u8>().unwrap_or(1), &sort, options)
                    .await
            }
        };
        match videos {
            Ok(v) => v,
            Err(e) => {
                println!("Error fetching videos: {}", e);
                vec![]
            }
        }
    }

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