"""Mariner magnet command."""

import logging

import pyperclip
from cliff import command

from mariner.utils import color


class Magnet(command.Command):
    """Copy magnet link with given ID to clipboard."""

    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", help="ID of the magnet link to copy", type=int)
        return parser

    def take_action(self, parsed_args):
        """Copy chosen magnet link to clipboard.

        Args:
            parsed_args: List of parsed arguments.

        """
        tid = parsed_args.ID
        torrent = self.app.engine.result(tid)
        self.log.debug("tid=%s torrent=%s", tid, torrent)
        link = torrent.magnet or torrent.download
        if not link:
            self.log.warning(
                color.yellow(f"{torrent.name} has no magnet link or download URL."),
            )
            return

        try:
            pyperclip.copy(link)
        except pyperclip.PyperclipException:
            self.log.error("Could not copy to clipboard. Link: %s", link)
            return

        if torrent.magnet:
            self.log.info(
                f"Copied {color.yellow(torrent.name)} magnet link to clipboard.",
            )
        else:
            self.log.warning(color.yellow(f"{torrent.name} has no magnet link."))
            self.log.info(
                f"Copied {color.yellow(torrent.name)} torrent URL instead.",
            )
