<?php
namespace Engine\Logger;

/**
 * Class for logging errors in Database
 * @author dan
 */
class DbEmulated extends \Engine\Logger\File
{
	protected $fileHandle = null;
	protected $fullFilePath = null;

	protected $messageIndex = 0;

	/**
	 * Constructor
	 */
	public function __construct()
	{
		parent::__construct();

		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		$this->directory = realpath($CFG['logger']['pathToRoot'])."/DbEmulated/";
	}

	/**
	 * Compose the complete file path
	 * @param string $level
	 * @return string
	 */
	protected function getRealFullFilepath($level, $logSession)
	{
		$fullFilePath = $this->directory.$logSession;

		// create dir, if needed
		clearstatcache();
		if (!\Engine\Dir::check($this->directory)) {
			\Engine\Dir::create($this->directory);
		}

		return $fullFilePath;
	}

	/**
	 * Write to file
	 * {@inheritDoc}
	 * @see \Engine\Logger\File::writeRawMessage()
	 */
	public function writeRawMessage($fields)
	{
		if ($fields['stacktrace']) {
			// remove the 'args' argument, because it takes up a lot of spae in the serialized output, and we cannot use it anyway in the log viewer
			foreach ($fields['stacktrace'] as $k=>$trace) {
				$fields['stacktrace'][$k]['args'] = [];
			}
		}

		// re-check folder on each access, in case the app admin model has deleted it
		$this->fullFilePath = $this->getRealFullFilepath($fields['level'], $fields['logSession']);
		file_put_contents(sprintf('%s %06d%s', $this->fullFilePath, $this->messageIndex++, ".ser.log"), serialize($fields));
		return true;
	}
}
