#!/usr/bin/python3
import logging

from mini_buildd import cli, client, events, util

LOG = logging.getLogger("mini_buildd")

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


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

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

        self._add_endpoint(self.parser)
        self.parser.add_argument("-A", "--after", type=util.Datetime.parse, action="store", help=f"Also show past events after this date. {util.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 [events.Type[t] for t in names] if names else None

        clnt = client.Client(self.args.endpoint)
        for event in clnt.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(util.json_pretty(event.to_json()))


if __name__ == "__main__":
    CLI().run()
