<?php

use Phalcon\Events\Event;
use Phalcon\Mvc\Micro;
use Phalcon\Logger\Formatter\Line as LineFormatter;

/**
 * LoggingMiddleware
 *
 * Processes the 404s
 */
class BaseKvLogger
{
	protected $logger;
	protected $requestId;
	protected $separator = '~$~';

	protected $params = [];
	protected $blacklist = ['password', 'authorization'];
	protected $censored_value = '******';
	protected $log_type = 'METRIC';

	public function __construct($logger, $requestId)
	{
		$this->logger = $logger;
		$this->requestId = $requestId;

		$formatter = new LineFormatter(
			'timestamp=%date%' . $this->separator .
				'type=%type%' . $this->separator .
				'%message%'
		);

		$logger->setFormatter($formatter);
	}

	public function addItem($key, $value, $namespace = '')
	{
		$final_value = $value;

		if (in_array(strtolower($key), $this->blacklist)) {
			$final_value = $this->censored_value;
		}

		$this->params[$namespace . $key] = $final_value;
	}

	public function addArray($namespace, $array)
	{
		foreach ($array as $key => $value) {
			$this->addItem($key, $value, $namespace);
		}
	}

	public function critical($message = NULL, $isFlush = TRUE)
	{
		return $this->write('critical', $message, $isFlush);
	}

	public function emergency($message = NULL, $isFlush = TRUE)
	{
		return $this->write('emergency', $message, $isFlush);
	}

	public function debug($message = NULL, $isFlush = TRUE)
	{
		return $this->write('debug', $message, $isFlush);
	}

	public function error($message = NULL, $isFlush = TRUE)
	{
		return $this->write('error', $message, $isFlush);
	}

	public function info($message = NULL, $isFlush = TRUE)
	{
		return $this->write('info', $message, $isFlush);
	}

	public function notice($message = NULL, $isFlush = TRUE)
	{
		return $this->write('notice', $message, $isFlush);
	}

	public function warning($message = NULL, $isFlush = TRUE)
	{
		return $this->write('warning', $message, $isFlush);
	}

	private function arrayToString($array)
	{
		if (!is_array($array))
			return '"' . $array . '"';

		$res = "";
		foreach ($array as $key => $item) {
			if (strlen($res) > 0)
				$res .= ", ";

			$res .= $key . " => " . $this->arrayToString($item);
		}
		return "[ " . $res . " ]";
	}

	private function write($level = "debug", $message = NULL, $isFlush = TRUE)
	{
		$logMessage = "";
		if (!empty($this->requestId))
			$logMessage = 'request_id=' . $this->requestId . $this->separator;

		$logMessage .= 'level=' . $level . $this->separator;

		if (!empty($message)) {
			$logMessage = $logMessage . 'message=' . $message . $this->separator;
		}

		foreach ($this->params as $key => $value) {
			$string_value = $value;

			if (is_array($value) || is_object($value)) {
				$string_value = $this->arrayToString($value);
			}

			$logMessage = $logMessage . $key . '=' . addslashes($string_value) . $this->separator;
		}

		$this->logger->$level($logMessage);

		if ($isFlush) {
			$this->flush();
		}
	}

	public function flush()
	{
		$this->params = [];
	}
}
