#!/usr/bin/env python
"""LICENSE
Copyright 2016 Hermann Krumrey <hermann@krumreyh.com>

This file is part of xdcc-dl.

xdcc-dl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

xdcc-dl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with xdcc-dl.  If not, see <http://www.gnu.org/licenses/>.
LICENSE"""

import argparse
from requests.exceptions import ConnectionError
from puffotter.init import cli_start, argparse_add_verbosity
from xdcc_dl import sentry_dsn
from xdcc_dl.xdcc.exceptions import DownloadIncomplete
from xdcc_dl.helper import set_throttle_value, set_logging_level, prepare_packs
from xdcc_dl.entities import XDCCPack
from xdcc_dl.logging import Logger
from xdcc_dl.xdcc import download_packs
from xdcc_dl.pack_search.SearchEngine import SearchEngineType


def main(args: argparse.Namespace):
    """
    Conducts a XDCC pack search with the option to immediately download any
    found packs
    :param args: The command line arguments
    :return: None
    """
    try:
        set_logging_level(args.quiet, args.verbose, args.debug, args.silent)
        set_throttle_value(args.throttle)

        search_engine = SearchEngineType.resolve(args.search_engine)

        results = search_engine.search(args.search_term)
        for i, result in enumerate(results):
            Logger().print("{}: {}".format(i + 1, result))

        selection = input("Enter the packs to download: ")
        parsepacks = XDCCPack.from_xdcc_message(
            "/msg A xdcc send #{}".format(selection)
        )

        packs = []
        for pack in parsepacks:  # type: XDCCPack
            packs.append(results[pack.packnumber - 1])
        prepare_packs(packs, args.out)

        for pack in packs:
            Logger().info("Downloading pack {}".format(pack))

        download_packs(
            packs,
            timeout=args.timeout,
            fallback_channel=args.fallback_channel
        )

    except ConnectionError:
        print("Connection Error, could not conduct search")
    except DownloadIncomplete:
        Logger().warning("Download incomplete.")
        raise KeyboardInterrupt()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("search_term", help="The term to search for")
    parser.add_argument("--search-engine",
                        default=SearchEngineType.HORRIBLESUBS.name.lower(),
                        choices=SearchEngineType.choices(True),
                        help="The Search Engine to use")
    parser.add_argument("-s", "--server",
                        default="irc.rizon.net",
                        help="Specifies the IRC Server. "
                             "Defaults to irc.rizon.net")
    parser.add_argument("-o", "--out",
                        help="Specifies the target file. "
                             "Defaults to the pack's file name. "
                             "When downloading multiple packs, index "
                             "numbers will be appended to the filename")
    parser.add_argument("-t", "--throttle",
                        help="Limits the download speed of xdcc-dl. "
                             "Append K,M or G for more convenient units")
    parser.add_argument("--timeout", default=120, type=int,
                        help="Sets a timeout for starting the download")
    parser.add_argument("--silent", action="store_true",
                        help="Disables all print output")
    parser.add_argument("--fallback-channel",
                        help="Fallback channel in case ")
    argparse_add_verbosity(parser)
    cli_start(
        main, parser,
        sentry_dsn=sentry_dsn,
        package_name="xdcc-dl",
        exit_msg="Thanks for using xdcc-dl!"
    )
