use crate::DbPool;
use crate::api::ClientVersion;
use crate::providers::Provider;
use crate::status::*;
use crate::util::cache::VideoCache;
use crate::util::discord::{format_error_chain, send_discord_error_report};
use crate::util::requester::Requester;
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::sync::{Arc, RwLock};
use std::{thread, vec};
use titlecase::Titlecase;

pub const CHANNEL_METADATA: crate::providers::ProviderChannelMetadata =
    crate::providers::ProviderChannelMetadata {
        group_id: "studio-network",
        tags: &["studio", "hd", "scenes"],
    };

error_chain! {
    foreign_links {
        Io(std::io::Error);
        HttpRequest(wreq::Error);
        Json(serde_json::Error);
    }
    errors {
        Parse(msg: String) {
            description("parse error")
            display("parse error: {}", msg)
        }
    }
}

#[derive(Debug, Clone)]
pub struct HqpornerProvider {
    url: String,
    stars: Arc<RwLock<Vec<FilterOption>>>,
    categories: Arc<RwLock<Vec<FilterOption>>>,
}

impl HqpornerProvider {
    pub fn new() -> Self {
        let provider = HqpornerProvider {
            url: "https://hqporner.com".to_string(),
            stars: Arc::new(RwLock::new(vec![])),
            categories: Arc::new(RwLock::new(vec![])),
        };
        provider.spawn_initial_load();
        provider
    }

    fn spawn_initial_load(&self) {
        let url = self.url.clone();
        let stars = Arc::clone(&self.stars);
        let categories = Arc::clone(&self.categories);

        thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build();

            if let Ok(runtime) = rt {
                runtime.block_on(async move {
                    if let Err(e) = Self::load_stars(&url, stars).await {
                        eprintln!("load_stars failed: {e}");
                    }
                    if let Err(e) = Self::load_categories(&url, categories).await {
                        eprintln!("load_categories failed: {e}");
                    }
                });
            }
        });
    }

    async fn load_stars(base_url: &str, stars: Arc<RwLock<Vec<FilterOption>>>) -> Result<()> {
        let mut requester = Requester::new();
        let text = requester
            .get(&format!("{}/girls", base_url), None)
            .await
            .map_err(|e| Error::from(format!("Request failed: {}", e)))?;

        let stars_div = text
            .split("<span>Girls</span>")
            .last()
            .and_then(|s| s.split("</ul>").next())
            .ok_or_else(|| Error::from("Could not find stars div"))?;

        for stars_element in stars_div.split("<li ").skip(1) {
            let star_id = stars_element
                .split("href=\"/actress/")
                .nth(1)
                .and_then(|s| s.split('"').next())
                .map(|s| s.to_string());

            let star_name = stars_element
                .split("<a ")
                .nth(1)
                .and_then(|s| s.split('>').nth(1))
                .and_then(|s| s.split('<').next())
                .map(|s| s.to_string());

            if let (Some(id), Some(name)) = (star_id, star_name) {
                Self::push_unique(&stars, FilterOption { id, title: name });
            }
        }
        Ok(())
    }

    async fn load_categories(
        base_url: &str,
        categories: Arc<RwLock<Vec<FilterOption>>>,
    ) -> Result<()> {
        let mut requester = Requester::new();
        let text = requester
            .get(&format!("{}/categories", base_url), None)
            .await
            .map_err(|e| Error::from(format!("Request failed: {}", e)))?;

        let categories_div = text
            .split("<span>Categories</span>")
            .last()
            .and_then(|s| s.split("</ul>").next())
            .ok_or_else(|| Error::from("Could not find categories div"))?;

        for categories_element in categories_div.split("<li ").skip(1) {
            let category_id = categories_element
                .split("href=\"/category/")
                .nth(1)
                .and_then(|s| s.split('"').next())
                .map(|s| s.to_string());

            let category_name = categories_element
                .split("<a ")
                .nth(1)
                .and_then(|s| s.split('>').nth(1))
                .and_then(|s| s.split('<').next())
                .map(|s| s.titlecase());

            if let (Some(id), Some(name)) = (category_id, category_name) {
                Self::push_unique(&categories, FilterOption { id, title: name });
            }
        }
        Ok(())
    }

    fn build_channel(&self, _clientversion: ClientVersion) -> Channel {
        Channel {
            id: "hqporner".to_string(),
            name: "HQPorner".to_string(),
            description: "HD Porn Videos Tube".to_string(),
            premium: false,
            favicon: "https://www.google.com/s2/favicons?sz=64&domain=hqporner.com".to_string(),
            status: "active".to_string(),
            categories: self
                .categories
                .read()
                .map(|c| c.iter().map(|o| o.title.clone()).collect())
                .unwrap_or_default(),
            options: vec![],
            nsfw: true,
            cacheDuration: None,
            ytdlpCommand: Some("yt-dlp --impersonate chrome-120".to_string())
        }
    }

    fn push_unique(target: &Arc<RwLock<Vec<FilterOption>>>, item: FilterOption) {
        if let Ok(mut vec) = target.write() {
            if !vec.iter().any(|x| x.id == item.id) {
                vec.push(item);
            }
        }
    }

    async fn get(
        &self,
        cache: VideoCache,
        page: u8,
        _sort: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let video_url = format!("{}/hdporn/{}", self.url, page);
        if let Some((time, items)) = cache.get(&video_url) {
            if time.elapsed().unwrap_or_default().as_secs() < 300 {
                return Ok(items.clone());
            }
        }

        let mut requester = options.requester.clone().ok_or("No requester")?;
        let text = requester
            .get(&video_url, None)
            .await
            .map_err(|e| Error::from(format!("Request failed: {}", e)))?;

        let video_items = self.get_video_items_from_html(text, &options).await;
        if !video_items.is_empty() {
            cache.insert(video_url, video_items.clone());
        }
        Ok(video_items)
    }

    async fn query(
        &self,
        cache: VideoCache,
        page: u8,
        query: &str,
        options: ServerOptions,
    ) -> Result<Vec<VideoItem>> {
        let search_string = query.trim().to_lowercase();
        let mut video_url = format!("{}/?q={}&p={}", self.url, search_string, page);

        if let Ok(stars) = self.stars.read() {
            if let Some(star) = stars
                .iter()
                .find(|s| s.title.to_lowercase() == search_string)
            {
                video_url = format!("{}/actress/{}/{}", self.url, star.id, page);
            }
        }
        if let Ok(cats) = self.categories.read() {
            if let Some(cat) = cats
                .iter()
                .find(|c| c.title.to_lowercase() == search_string)
            {
                video_url = format!("{}/category/{}/{}", self.url, cat.id, page);
            }
        }

        if let Some((time, items)) = cache.get(&video_url) {
            if time.elapsed().unwrap_or_default().as_secs() < 300 {
                return Ok(items.clone());
            }
        }

        let mut requester = options.requester.clone().ok_or("No requester")?;
        let text = requester
            .get(&video_url, None)
            .await
            .map_err(|e| Error::from(format!("Request failed: {}", e)))?;

        let video_items = self.get_video_items_from_html(text, &options).await;
        if !video_items.is_empty() {
            cache.insert(video_url, video_items.clone());
        }
        Ok(video_items)
    }

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

        let raw_videos: Vec<String> = html
            .split("id=\"footer\"")
            .next()
            .and_then(|s| s.split("<section class=\"box features\">").nth(2))
            .map(|s| {
                s.split("<section class=\"box feature\">")
                    .skip(1)
                    .map(|v| v.to_string())
                    .collect()
            })
            .unwrap_or_default();

        raw_videos
            .into_iter()
            .filter_map(|seg| self.get_video_item(seg, options).ok())
            .collect()
    }

    fn get_video_item(&self, seg: String, options: &ServerOptions) -> Result<VideoItem> {
        let detail_url = format!(
            "{}{}",
            self.url,
            seg.split("<a href=\"")
                .nth(1)
                .and_then(|s| s.split('"').next())
                .ok_or_else(|| ErrorKind::Parse(format!("url \n{seg}").into()))?
        );
        let title_raw = seg
            .split("<h3 class=\"meta-data-title\">")
            .nth(1)
            .and_then(|s| s.split('>').nth(1))
            .and_then(|s| s.split('<').next())
            .ok_or_else(|| ErrorKind::Parse(format!("title \n{seg}").into()))?;
        let title = decode(title_raw.as_bytes())
            .to_string()
            .unwrap_or_else(|_| title_raw.to_string())
            .titlecase();

        let id = detail_url
            .split('/')
            .nth(4)
            .and_then(|s| s.split('.').next())
            .ok_or_else(|| ErrorKind::Parse(format!("id \n{seg}").into()))?
            .to_string();
        let thumb_raw = seg
            .split("onmouseleave='defaultImage(\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .ok_or_else(|| ErrorKind::Parse(format!("thumb \n{seg}").into()))?;
        let thumb_abs = if thumb_raw.starts_with("//") {
            format!("https:{}", thumb_raw)
        } else if thumb_raw.starts_with("http://") || thumb_raw.starts_with("https://") {
            thumb_raw.to_string()
        } else {
            format!("https://{}", thumb_raw.trim_start_matches('/'))
        };
        let thumb = match thumb_abs.strip_prefix("https://") {
            Some(path) => crate::providers::build_proxy_url(options, "hqporner-thumb", path),
            None => thumb_abs,
        };
        let raw_duration = seg
            .split("<span class=\"icon fa-clock-o meta-data\">")
            .nth(1)
            .and_then(|s| s.split("s<").next())
            .map(|s| s.replace("m ", ":"))
            .unwrap_or_default();
        let duration = parse_time_to_seconds(&raw_duration).unwrap_or(0) as u32;

        let stripped_detail_url = crate::providers::strip_url_scheme(&detail_url);
        let proxied_url = crate::providers::build_proxy_url(
            options,
            "hqporner",
            &stripped_detail_url,
        );

        let quality_target = |quality: &str| -> String {
            format!("{stripped_detail_url}/__quality__/{quality}")
        };
        let formats = vec![
            VideoFormat::new(
                crate::providers::build_proxy_url(options, "hqporner", &quality_target("1080")),
                "1080p".to_string(),
                "mp4".to_string(),
            )
            .format_id("1080p".to_string())
            .format_note("1080p Full HD".to_string()),
            VideoFormat::new(
                crate::providers::build_proxy_url(options, "hqporner", &quality_target("720")),
                "720p".to_string(),
                "mp4".to_string(),
            )
            .format_id("720p".to_string())
            .format_note("720p HD".to_string()),
            VideoFormat::new(
                crate::providers::build_proxy_url(options, "hqporner", &quality_target("360")),
                "360p".to_string(),
                "mp4".to_string(),
            )
            .format_id("360p".to_string())
            .format_note("360p".to_string()),
        ];

        Ok(VideoItem::new(
            id,
            title,
            proxied_url,
            "hqporner".into(),
            thumb,
            duration,
        )
        .formats(formats))
    }
}

#[async_trait]
impl Provider for HqpornerProvider {
    async fn get_videos(
        &self,
        cache: VideoCache,
        _pool: DbPool,
        sort: String,
        query: Option<String>,
        page: String,
        _per_page: String,
        options: ServerOptions,
    ) -> Vec<VideoItem> {
        let page_num = page.parse::<u8>().unwrap_or(1);
        let res = match query {
            Some(q) => self.query(cache, page_num, &q, options).await,
            None => self.get(cache, page_num, &sort, options).await,
        };
        res.unwrap_or_else(|e| {
            eprintln!("Hqporner error: {e}");
            let _ = send_discord_error_report(
                e.to_string(),
                Some(format_error_chain(&e)),
                None,
                None,
                file!(),
                line!(),
                module_path!(),
            );
            vec![]
        })
    }

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