"""Mariner download command."""

import logging

from cliff import lister

from mariner.services.downloader import Service as DownloadService
from mariner.utils import color


class Download(lister.Lister):
    """Download torrent with given ID."""

    log = logging.getLogger(__name__)

    def get_parser(self, prog_name):
        """Add arguments to argument parser.

        Args:
            prog_name: Application name.

        Returns:
            Instance of argument parser.

        """
        parser = super().get_parser(prog_name)
        parser.add_argument(
            "ID",
            nargs="+",
            help="ID of the torrent to download",
            type=int,
        )
        parser.add_argument(
            "--path",
            "-p",
            nargs="?",
            help="Path to downloads torrent files to",
            default=self.app.config["download_path"],
        )
        return parser

    def take_action(self, parsed_args):
        """Download chosen torrent.

        Args:
            parsed_args: List of parsed arguments.

        Returns:
            List of downloaded torrents and the location where
            they were saved.

        """
        download_path = parsed_args.path
        torrents = []
        for tid in parsed_args.ID:
            torrent = self.app.engine.result(tid)
            self.log.debug("tid=%s torrent=%s", tid, torrent)
            if torrent.download:
                torrents.append(torrent)
                self.log.debug("Torrent appended.")
                self.log.info(f"Downloading torrent {color.yellow(torrent.name)}.")
            else:
                self.log.warning(
                    color.yellow(
                        f"No torrent for {torrent.name}. Use magnet link instead.",
                    ),
                )

        files = [(t.download, t.filename) for t in torrents]
        self.log.debug("files=%s download_path=%s", files, download_path)
        downloader = DownloadService(
            client=self.app.http_client,
            download_path=download_path,
        )
        filelist = downloader.download(files)

        headers = ("Name", "Saved to")
        colored_headers = [color.cyan(h) for h in headers]
        columns = zip((color.yellow(t.name) for t in torrents), filelist, strict=False)
        return (colored_headers, columns)
