#! /usr/bin/env python3


import argparse
import enum
import json
import re
import sys


class OutputModes(enum.Enum):
    @classmethod
    def _interactive(cls, log_lines, pattern):
        print("\n\n --> log_events \n\n")

        log_events = list(matching_events(log_lines, pattern))

        from IPython import embed
        embed(colors="neutral")
    interactive = _interactive

    @classmethod
    def _cli_output(cls, log_lines, pattern):
        for event in matching_events(log_lines, pattern):
            print(event)
    cli_output = _cli_output


def main(pattern, filename, mode):
    def interactive_mode():
        print("\n\n --> log_events \n\n")

        log_events = list(matching_events(log_lines, pattern))

        from IPython import embed
        embed(colors="neutral")

    def cli_display_mode():
        for event in matching_events(log_lines, pattern):
            print(event)

    with open(filename) as fh:
        log_lines = json.load(fh)["events"]

    mode(log_lines, pattern)


def matching_events(iter_, pattern):
    print(pattern)
    matcher = re.compile(pattern)
    for line in iter_:
        if matcher.search(json.dumps(line)) is not None:
            line["message"] = json.loads(line["message"])
            yield line


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--interactive", action="store_true")
    parser.add_argument("pattern")
    parser.add_argument("file")

    args = parser.parse_args()
    if args.interactive:
        mode = OutputModes.interactive
    else:
        mode = OutputModes.cli_output

    main(args.pattern, args.file, mode)
