#!/usr/bin/python3
# pylint: disable=invalid-name  # https://github.com/PyCQA/pylint/issues/516
import json
import datetime
import logging

import dateutil.parser

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 stop when criteria is met."


def parse_since(date_string):
    if date_string == "all":
        since = datetime.datetime(datetime.MINYEAR + 1, 1, 1)
        return since.astimezone()
    since = dateutil.parser.parse(date_string)
    if mini_buildd.misc.datetime_is_naive(since):
        since = since.astimezone()
        LOG.info(f"Naive timestamp converted: {date_string} => {since}")
    return since


class CLI(mini_buildd.cli.CLI):
    def __init__(self):
        super().__init__("mini-buildd-events", DESCRIPTION)

        self._add_endpoint(self.parser)
        self.parser.add_argument("-C", "--since", type=parse_since, action="store", help="Replay past events since this date (formats like 'date --iso-8601=ns' work fine). Use 'all' to replay all.")
        self.parser.add_argument("-T", "--types", choices=[t.name for t in list(mini_buildd.events.Type)], action="store", nargs="+", help="Types to search for")
        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("-D", "--distribution", action="store", help="Distribution filter")
        self.parser.add_argument("-s", "--stop", action="store_true", default=False, help="Stop on 1st matching event")

    def runcli(self):
        client = mini_buildd.client.Client(self.args.endpoint)
        for event in client.events_iter(since=self.args.since,
                                        types=[mini_buildd.events.Type[type] for type in self.args.types] if self.args.types else None,
                                        source=self.args.source,
                                        version=self.args.source_version,
                                        minimal_version=self.args.minimal_version,
                                        distribution=self.args.distribution,
                                        stop=self.args.stop):
            print(json.dumps(event.to_json(), indent=2))


CLI().run()
