#!/usr/bin/python3
import logging

import mini_buildd.misc
import mini_buildd.client
import mini_buildd.events
import mini_buildd.cli

LOG = logging.getLogger("mini_buildd")

#: Needed for man page hack in setup.py
DESCRIPTION = "Monitor events. Optionally exit when criteria is met."


class CLI(mini_buildd.cli.CLI):
    TYPE_CHOICES = [t.name for t in list(mini_buildd.events.Type)]

    def __init__(self):
        super().__init__("mini-buildd-events", DESCRIPTION)

        self._add_endpoint(self.parser)
        self.parser.add_argument("-A", "--after", type=mini_buildd.misc.Datetime.parse, action="store", help=f"Also show past events after this date. {mini_buildd.misc.Datetime.parse.__doc__}.")
        self.parser.add_argument("-T", "--types", choices=self.TYPE_CHOICES, action="store", nargs="+", help="Types filter")
        self.parser.add_argument("-D", "--distribution", action="store", help="Distribution filter")
        self.parser.add_argument("-S", "--source", action="store", help="Source package name filter")
        self.parser.add_argument("-V", "--source-version", action="store", help="Version filter")
        self.parser.add_argument("-M", "--minimal-version", action="store", help="Minimal version filter")
        self.parser.add_argument("-E", "--exit-on", choices=self.TYPE_CHOICES, action="store", nargs="+", help="Types to exit on")
        self.parser.add_argument("-F", "--fail-on", choices=self.TYPE_CHOICES, action="store", nargs="+", help="Types to (return and) fail on")

    def runcli(self):
        def n2t(names):
            return [mini_buildd.events.Type[t] for t in names] if names else None

        client = mini_buildd.client.Client(self.args.endpoint)
        for event in client.ievents(after=self.args.after,
                                    types=n2t(self.args.types),
                                    distribution=self.args.distribution,
                                    source=self.args.source,
                                    version=self.args.source_version,
                                    minimal_version=self.args.minimal_version,
                                    exit_on=n2t(self.args.exit_on),
                                    fail_on=n2t(self.args.fail_on)):
            print(mini_buildd.misc.json_pretty(event.to_json()))


CLI().run()
