use ntex::web;
use wreq::Version;

use crate::util::requester::Requester;

#[derive(Debug, Clone)]
pub struct JavtifulProxy {}

impl JavtifulProxy {
    pub fn new() -> Self {
        JavtifulProxy {}
    }

    pub async fn get_video_url(
        &self,
        url: String,
        requester: web::types::State<Requester>,
    ) -> String {
        let mut requester = requester.get_ref().clone();
        let url = "https://javtiful.com/".to_string() + &url;
        let text = requester.get(&url, None).await.unwrap_or("".to_string());
        if text.is_empty() {
            return "".to_string();
        }
        let video_id = url.split('/').nth(4).unwrap_or("").to_string();

        let token = text
            .split("data-csrf-token=\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .unwrap_or("")
            .to_string();

        let form = wreq::multipart::Form::new()
            .text("video_id", video_id.clone())
            .text("pid_c", "".to_string())
            .text("token", token.clone());
        let resp = match requester
            .post_multipart(
                "https://javtiful.com/ajax/get_cdn",
                form,
                vec![("Referer".to_string(), url.to_string())],
                Some(Version::HTTP_11),
            )
            .await
        {
            Ok(r) => r,
            Err(_) => return "".to_string(),
        };
        let text = resp.text().await.unwrap_or_default();
        let json: serde_json::Value =
            serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
        let video_url = json
            .get("playlists")
            .map(|v| v.to_string().replace("\"", ""))
            .unwrap_or_default();

        return video_url;
    }
}
