<?php
/**
 * @file
 * Trivial logger for easier debug.
 */

namespace Osinet\ClassGrapher;


use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Psr\Log\LogLevel;

class Logger implements LoggerInterface {

  use LoggerTrait;

  /**
   * Map Syslog LOG_* constants to PSR/3 log levels.
   */
  public const Levels = [
    LOG_EMERG => LogLevel::EMERGENCY,
    LOG_ALERT => LogLevel::ALERT,
    LOG_CRIT => LogLevel::CRITICAL,
    LOG_ERR => LogLevel::ERROR,
    LOG_WARNING => LogLevel::WARNING,
    LOG_NOTICE => LogLevel::NOTICE,
    LOG_INFO => LogLevel::INFO,
    LOG_DEBUG => LogLevel::DEBUG,
  ];

  public $fDebugLevel;

  public function __construct($debugLevel = LOG_WARNING) {
    $this->debugLevel($debugLevel);
  }

  /**
   * Get or Set the current debug level.
   *
   * @param int $level
   *   LOG_EMERG to LOG_DEBUG. If NULL, do not set it.
   *
   * @return
   *   The value of the debug level before this function was called.
   */
  public function debugLevel($level = NULL) {
    $ret = $this->fDebugLevel;

    if (isset($level)) {
      if ($level < LOG_EMERG) {
        $level = LOG_EMERG;
      }
      if ($level > LOG_DEBUG) {
        $level = LOG_DEBUG;
      }
      $this->fDebugLevel = $level;
    }

    return $ret;
  }

  /**
   * Output a message on STDERR if its relevance is above minimum level.
   *
   * @param string $message
   * @param int $level
   *   Defined in RFC 3164, section 4.1.1 "Severity". But compare with Drupal 7
   *   WATCHDOG_* constants in includes/bootstrap.inc for an explanation about
   *   syslog constants in PHP.
   */
  public function legacyLog($message = "\n", $level = LOG_INFO) {
    $psr3Level = static::Levels[$level] ?? LogLevel::ERROR;
    $this->log($psr3Level, $message);
  }

  /**
   * @param mixed $level
   * @param string $message
   * @param array $context
   */
  public function log($level, $message, array $context = []) {
    if ($level <= $this->fDebugLevel) {
      fputs(STDERR, $message);
      fflush(STDERR);
    }
  }

}