# Copyright (c) 2024  Kent State University CAE-NetLab

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import logging
import logging.handlers

import blinker

from .config import CFG

class _LogManager():
  def __init__ (self):
    self._log = logging.getLogger("mtraf")
    self._lhandle = logging.handlers.RotatingFileHandler(CFG.get("log.path"),
                                                   maxBytes = CFG.get("log.file-maxbytes"),
                                                   backupCount = CFG.get("log.file-backups"))
    self._lhandle.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] - %(message)s"))

    self._log.addHandler(self._lhandle)
    self._log.setLevel(CFG.get("log.file-level"))

    self._signal_status = blinker.signal("status.update")
    self._signal_status.connect(self._writeLogEntry)

    self._signal_cfgupdate = blinker.signal("config.update")
    self._signal_cfgupdate.connect(self._reconfig)


  def _writeLogEntry (self, sender, level = logging.INFO, message = ""):
    self._log.log(level, message)

  def _reconfig (self, sender):
    self._log.setLevel(CFG.get("log.file-level"))
    if self._lhandle.baseFilename != CFG.get("log.path"):
      self._lhandle.baseFilename = CFG.get("log.path")
      self._lhandle.doRollover()
    self._lhandle.maxBytes = CFG.get("log.file-maxbytes")
    self._lhandle.backupCount = CFG.get("log.file-backups")
    self._signal_status.send(level = logging.DEBUG, message = "Logging reconfigured on config update")


LOGM = _LogManager()
