use ntex::web::{self, HttpRequest};

use crate::proxies::javtiful::JavtifulProxy;
use crate::proxies::spankbang::SpankbangProxy;
use crate::proxies::sxyprn::SxyprnProxy;
use crate::proxies::*;
use crate::util::requester::Requester;

pub fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::resource("/sxyprn/{endpoint}*")
            .route(web::post().to(proxy2redirect))
            .route(web::get().to(proxy2redirect)),
    )
    .service(
        web::resource("/javtiful/{endpoint}*")
            .route(web::post().to(proxy2redirect))
            .route(web::get().to(proxy2redirect)),
    )
    .service(
        web::resource("/spankbang/{endpoint}*")
            .route(web::post().to(proxy2redirect))
            .route(web::get().to(proxy2redirect)),
    )
    .service(
        web::resource("/noodlemagazine/{endpoint}*")
            .route(web::post().to(crate::proxies::noodlemagazine::serve_media))
            .route(web::get().to(crate::proxies::noodlemagazine::serve_media)),
    )
    .service(
        web::resource("/hanime-cdn/{endpoint}*")
            .route(web::post().to(crate::proxies::hanimecdn::get_image))
            .route(web::get().to(crate::proxies::hanimecdn::get_image)),
    )
    .service(
        web::resource("/hqporner-thumb/{endpoint}*")
            .route(web::post().to(crate::proxies::hqpornerthumb::get_image))
            .route(web::get().to(crate::proxies::hqpornerthumb::get_image)),
    )
    .service(
        web::resource("/porndish-thumb/{endpoint}*")
            .route(web::post().to(crate::proxies::porndishthumb::get_image))
            .route(web::get().to(crate::proxies::porndishthumb::get_image)),
    );
}

async fn proxy2redirect(
    req: HttpRequest,
    requester: web::types::State<Requester>,
) -> Result<impl web::Responder, web::Error> {
    let proxy = get_proxy(req.uri().to_string().split("/").collect::<Vec<&str>>()[2]).unwrap();
    let endpoint = req.match_info().query("endpoint").to_string();
    let video_url = match proxy.get_video_url(endpoint, requester).await {
        url if url != "" => url,
        _ => "Error".to_string(),
    };
    Ok(web::HttpResponse::Found()
        .header("Location", video_url)
        .finish())
}

fn get_proxy(proxy: &str) -> Option<AnyProxy> {
    match proxy {
        "sxyprn" => Some(AnyProxy::Sxyprn(SxyprnProxy::new())),
        "javtiful" => Some(AnyProxy::Javtiful(JavtifulProxy::new())),
        "spankbang" => Some(AnyProxy::Spankbang(SpankbangProxy::new())),
        _ => None,
    }
}
