#
#   logactio  -  simple framework for doing configured action on certain
#                log file events
#
# SPDX-FileCopyrightText: Copyright 2012-  David Sommerseth <dazo@eurephia.org>
# SPDX-License-Identifier: GPL-2.0-only
#

import sys
from LogActio import Message, ReporterQueue


class DefaultReporter(ReporterQueue.ReporterQueue):
    def __init__(self, config, logger=None):
        self.__alertprefix = config.get('prefix', '---> ')
        self.__log = logger
        super().__init__("DefaultReporter", "Default stdout reporter", self.__processqueue)


    def __processqueue(self):
        done = False

        # Process the message queue
        while not done:
            msg = self._QueueGet()

            if msg.MessageType() == Message.MSG_SHUTDOWN:
                done = True

            elif msg.MessageType() == Message.MSG_SEND:
                if not self.__log:
                    print(f"[DefaultReporter] {msg}")
                    sys.stdout.flush()
                else:
                    self.__log(0, f"[DefaultReporter] {msg}")


    def ProcessEvent(self, logfile, prefix, msg, count, threshold):
        # Format the report message
        if msg is None:
            text = f"{self.__alertprefix} [{logfile}] {prefix} ({count})"
        else:
            text = f"{self.__alertprefix} [{logfile}] {prefix} ({count}): {msg}"

        # Queue the message for sending
        self._QueueMsg(0, text)

