#!/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 puffotter.init import cli_start
from requests.exceptions import ConnectionError
from xdcc_dl import sentry_dsn
from xdcc_dl.pack_search.SearchEngine import SearchEngineType
from puffotter.units import human_readable_bytes


def main(args: argparse.Namespace):
    """
    Conducts a XDCC pack search
    :param args: The command line arguments
    :return: None
    """
    try:
        search_engine = SearchEngineType.resolve(args.search_engine)
        results = search_engine.search(args.search_term)
        for result in results:
            message = "{} [{}] (xdcc-dl \"{}\")".format(
                result.filename,
                human_readable_bytes(result.get_size()),
                result.get_request_message(True),
            )
            if result.server.address != "irc.rizon.net":
                message = message[0:-1]
                message += " --server " + result.server.address + ")"
            print(message)
    except ConnectionError:
        print("Connection Error, could not conduct search")
        raise KeyboardInterrupt()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("search_term", help="The term to search for")
    parser.add_argument("search_engine",
                        choices=SearchEngineType.choices(True),
                        help="The Search Engine to use")
    cli_start(
        main, parser,
        sentry_dsn=sentry_dsn,
        package_name="xdcc-dl",
        exit_msg="Thanks for using xdcc-dl!"
    )
