#!/usr/bin/env python3

"""add-scihub-torrents

Usage:
    add-scihub-torrents (HOSTNAME) (USERNAME) (PASSWORD)
    add-scihub-torrents -h

Examples:
    add-scihub-torrents "http://localhost:8080" "admin" "adminadmin"
    add-scihub-torrents "https://cat.seedhost.eu/lol/qbittorrent" "lol" "pw"

Options:
    -h, --help      show this help message and exit
"""

import os
import subprocess
from pathlib import Path

from docopt import docopt
from qbittorrent import Client

if __name__ == "__main__":
    args = docopt(__doc__)

    # Initialize client and login
    qb = Client(args["HOSTNAME"])
    qb.login(username=args["USERNAME"], password=args["PASSWORD"])

    # Get scihub torrent- files and display them with gum
    scihub_torrent_dir = Path.home().joinpath("scihub-torrent-urls")
    torrent_files = [x.name for x in scihub_torrent_dir.iterdir()]
    subproc_arg = [
        "gum",
        "choose",
        "--header='Select Sci Hub torrents'",
        "--height=13",
        "--no-limit",
    ]
    subproc_arg.extend(torrent_files)
    torrent_selection = (
        subprocess.run(subproc_arg, stdout=subprocess.PIPE, text=True)
        .stdout.strip()
        .splitlines()
    )

    # Read the contents of each file and put lines (which are URLs) into a list
    torrent_urls = list()
    for item in torrent_selection:
        with open(scihub_torrent_dir.joinpath(item), "r") as tf:
            urls = tf.readlines()
            torrent_urls.extend(urls)

    torrent_urls = [x.strip("\n") for x in torrent_urls]

    # Add urls to qBittorrent instance
    for url in torrent_urls:
        qb.download_from_link(url, category="scihub")
        print(f"Added {os.path.basename(url)}")