use clap::{crate_version, value_t, App, Arg};
use regex::Regex;
use std::{
    fs::File,
    io::{BufRead, BufReader},
    process,
};

fn main() {
    let matches = App::new("ph-dl")
        .version(crate_version!())
        .author("Miika Launiainen <miika.launiainen@gmail.com>")
        .about("Get highest quality direct link to download PH videos, or download them automatically.")
        .arg(
            Arg::with_name("url")
                .help("view key to the video or URL to the video/playlist")
                .required(true)
                .conflicts_with("file"),
        )
        .arg(
            Arg::with_name("download")
                .short("d")
                .long("download")
                .help("Download the video automatically"),
        )
        .arg(
            Arg::with_name("show_quality")
                .short("Q")
                .long("show_quality")
                .help("Print all available resolutions"),
        )
        .arg(
            Arg::with_name("quality")
                .short("q")
                .long("quality")
                .takes_value(true)
                .possible_values(&["1", "2", "3", "4"])
                .help("Use specific resolution"),
        )
        .arg(
            Arg::with_name("file")
                .short("f")
                .long("file")
                .takes_value(true)
                .help("Download videos from file")
                .conflicts_with("url"),
        )
        .get_matches();

    if matches.is_present("file") {
        download_from_file(value_t!(matches.value_of("file"), String).unwrap());
        process::exit(0);
    }

    let url = value_t!(matches.value_of("url"), String).unwrap();
    let download = matches.is_present("download");
    let show_quality = matches.is_present("show_quality");
    let quality = if matches.is_present("quality") {
        value_t!(matches.value_of("quality"), String).unwrap()
    } else {
        "none".to_string()
    };

    let url = check_for_ph_url(&url);

    ph_dl::run(url, download, show_quality, quality);
}

fn check_for_ph_url(url: &str) -> String {
    let normal_url =
        Regex::new(r"(https?://(www\.)?pornhub\.com/view_video\.php\?viewkey=[0-9a-ö]*)[/&]?")
            .unwrap();
    let playlist = Regex::new(r"https?://(www\.)pornhub.com/playlist/\d+").unwrap();

    if normal_url.is_match(url) {
        let url = match normal_url.captures(url) {
            Some(i) => i.get(1).unwrap().as_str().to_string(),
            None => "Error".to_string(),
        };
        url
    } else if playlist.is_match(url) {
        url.to_string()
    } else {
        return format!("https://www.pornhub.com/view_video.php?viewkey={}", url);
    }
}

fn download_from_file(path: String) {
    let file = File::open(&path);

    match file {
        Ok(file) => {
            let reader = BufReader::new(&file);
            for line in reader.lines() {
                let url = check_for_ph_url(line.unwrap().as_str());
                ph_dl::run(url, true, false, "none".to_string());
            }
        }
        Err(e) => {
            eprintln!("{}", e);
            process::exit(1);
        }
    };
}
