use crate::util::parse_abbreviated_number;
use crate::DbPool;
use crate::providers::Provider;
use crate::util::cache::VideoCache;
use crate::util::time::parse_time_to_seconds;
use crate::videos::{ServerOptions, VideoItem};
use error_chain::error_chain;
use htmlentity::entity::{ICodedDataTrait, decode};
use std::vec;
use async_trait::async_trait;

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

#[derive(Debug, Clone)]
pub struct PornhubProvider {
    url: String,
}
impl PornhubProvider {
    pub fn new() -> Self {
        PornhubProvider {
            url: "https://www.pornhub.com".to_string(),
        }
    }
    async fn get(
        &self,
        cache: VideoCache,
        page: u8,
        sort: &str,
        options:ServerOptions
    ) -> Result<Vec<VideoItem>> {
        let video_url = format!("{}/video?o={}&page={}", self.url, sort, page);
        let old_items = match cache.get(&video_url) {
            Some((time, items)) => {
                if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 {
                    println!("Cache hit for URL: {}", video_url);
                    return Ok(items.clone());
                } else {
                    items.clone()
                }
            }
            None => {
                vec![]
            }
        };

        let mut requester = options.requester.clone().unwrap();
        let text = requester.get(&video_url).await.unwrap();
        let video_items: Vec<VideoItem> = self.get_video_items_from_html(text.clone(),"<ul id=\"video");
        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 mut split_string = "<ul id=\"video";
        let search_string = query.to_lowercase().trim().replace(" ", "+");
        let mut video_url = format!("{}/video/search?search={}&page={}", self.url, search_string, page);
        if query.starts_with("@"){
            let url_parts = query[1..].split(":").collect::<Vec<&str>>();
            video_url = [self.url.to_string(), url_parts[0].to_string(), url_parts[1].replace(" ", "-").to_string(), "videos?page=".to_string()].join("/");
            video_url += &page.to_string();
            if query.contains("@model") || query.contains("@pornstar"){
                split_string = "mostRecentVideosSection";
            }
            if query.contains("@channels"){
                split_string = "<ul class=\"videos row-5-thumbs";
            }
        }

        if query.contains("@channels"){
            video_url += match sort {
                "mr" => "",
                "mv" => "&o=vi",
                "tr" => "&o=ra",
                _ => "",
            } 
        } else{
            video_url += match sort {
                "mr" => "",
                "mv" => "&o=mv",
                "tr" => "&o=tr",
                "lg" => "&o=lg",
                _ => "&o=mv",
            } 
        }

        // 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 = options.requester.clone().unwrap();
        let text = requester.get(&video_url).await.unwrap();
        let video_items: Vec<VideoItem> = self.get_video_items_from_html(text.clone(),split_string);
        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, split_string: &str) -> 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(split_string).collect::<Vec<&str>>()[1].split("Porn in German").collect::<Vec<&str>>()[0];
        let raw_videos = video_listing_content
            .split("class=\"pcVideoListItem ")
            .collect::<Vec<&str>>()[1..]
            .to_vec();
        for video_segment in &raw_videos {
            // let vid = video_segment.split("\n").collect::<Vec<&str>>();
            // for (index, line) in vid.iter().enumerate() {
            //     println!("Line {}: {}", index, line);
            // }
            if video_segment.contains("wrapVideoBlock"){
                continue; // Skip if the segment is a wrapVideoBlock
            }
            let video_url: String;
            if !video_segment.contains("<a href=\"") {
                let url_part = video_segment.split("data-video-vkey=\"").collect::<Vec<&str>>()[1]
                    .split("\"")
                    .collect::<Vec<&str>>()[0];
                video_url = format!("{}{}", self.url, url_part);
            }
            else{
                let url_part = video_segment.split("<a href=\"").collect::<Vec<&str>>()[1]
                    .split("\"")
                    .collect::<Vec<&str>>()[0];
                if url_part.is_empty() || url_part == "javascript:void(0)" {
                    continue;
                }
                video_url = format!("{}{}", self.url, url_part);
            }
            if video_url.starts_with("https://www.pornhub.comjavascript:void(0)") {
                continue;
            }
            let mut title = video_segment.split("\" title=\"").collect::<Vec<&str>>()[1]
                .split("\"")
                .collect::<Vec<&str>>()[0]
                .to_string();
            // html decode
            title = decode(title.as_bytes()).to_string().unwrap_or(title);
            let id = video_segment.split("data-video-id=\"").collect::<Vec<&str>>()[1]
                .split("\"")
                .collect::<Vec<&str>>()[0]
                .to_string();
            let raw_duration = video_segment.split("duration").collect::<Vec<&str>>()[1].split(">").collect::<Vec<&str>>()[1]
                    .split("<")
                    .collect::<Vec<&str>>()[0]
                    .to_string();
            let duration = parse_time_to_seconds(&raw_duration).unwrap_or(0) as u32;
            let view_part = match video_segment.split("iews\">").collect::<Vec<&str>>().len(){
                2 => video_segment.split("iews\">").collect::<Vec<&str>>()[1],
                3 => video_segment.split("iews\">").collect::<Vec<&str>>()[2],
                _ => "<var>0<", // Skip if the format is unexpected
            };
            let views = parse_abbreviated_number(view_part
                .split("<var>").collect::<Vec<&str>>()[1]
                .split("<")
                .collect::<Vec<&str>>()[0]).unwrap_or(0);

            let thumb = video_segment.split("src=\"").collect::<Vec<&str>>()[1]
                .split("\"")
                .collect::<Vec<&str>>()[0]
                .to_string();

            let uploaderBlock;
            let uploader_href;
            let mut tag = String::new();
            if video_segment.contains("videoUploaderBlock") {

                uploaderBlock = video_segment.split("videoUploaderBlock").collect::<Vec<&str>>()[1]
                    .to_string();
                uploader_href = uploaderBlock.split("href=\"").collect::<Vec<&str>>()[1]
                    .split("\"")
                    .collect::<Vec<&str>>()[0]
                    .split("/").collect::<Vec<&str>>();
                tag = format!("@{}:{}", uploader_href[1], uploader_href[2].replace("-", " "));

            }
            else{
                uploader_href = vec![];
            }


            let mut video_item = VideoItem::new(
                id,
                title,
                video_url.to_string(),
                "pornhub".to_string(),
                thumb,
                duration,
            )
            ;
            if views > 0 {
                video_item = video_item.views(views);
            }
            if !tag.is_empty() {
                video_item = video_item.tags(vec![tag])
                .uploader(uploader_href[2].to_string());
            }
            items.push(video_item);
        }
        return items;
    }


}

#[async_trait]
impl Provider for PornhubProvider {
    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; // Ignored in this implementation
        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![]
            }
        }
    }
}
