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

use crate::proxies::sxyprn::SxyprnProxy;
use crate::util::requester::Requester;
use crate::proxies::*;

pub fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::resource("/sxyprn/{endpoint}*")
            .route(web::post().to(sxyprn))
            .route(web::get().to(sxyprn)),
    )
    // .service(
    //     web::resource("/videos")
    //         // .route(web::get().to(videos_get))
    //         .route(web::post().to(videos_post)),
    // )
    ;
}


async fn sxyprn(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();
    println!("/proxy/sxyprn: endpoint={:?}", endpoint);
    let video_url = match proxy.get_video_url(endpoint, requester).await{
        url if url != "" => url,
        _ => "Error".to_string(),
    };
    Ok(web::HttpResponse::Found()
                    .header("Location", format!("https:{}", video_url))
                    .finish())
}

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