<?php
namespace Engine\Logger;

/**
 * Log errors into CSV files.
 * Supports pre-setting a header
 * @author Lucian Sirbu
 *
 */
class Csv extends \Engine\Logger\File
{
	protected $fileHeader = [
	];

	public function setFileHeader(array $fileHeader)
	{
		$this->fileHeader = $fileHeader;
		return $this;
	}

	public function getFileHeader()
	{
		return $this->fileHeader;
	}

	public function writeRawMessage($fields)
	{
		$fullFilePath = $this->getRealFullFilepath($fields['level'], $fields['logSession']).".csv";

		$errMessage = $this->composeErrorMessage($fields['level'], $fields['message'], $fields['context'], $fields['stacktrace'], $fields['idUser'], $fields['addTime'], $fields['logSession']);

		// create file
		if (!\Engine\File::check($fullFilePath)) {
			\Engine\File::create($fullFilePath);

			$fh = fopen($fullFilePath, "a+");
			if (!$fh) {
				throw new \Exception("Cannot write to {$fullFilePath}");
			}

			fputcsv($fh, array_keys($errMessage), ",", "\"", "");

			fclose($fh);
		}

		$fh = fopen($fullFilePath, "a+"); // TODO: \Engine\File::create can be used with "append"
		if (!$fh) {
			throw new \Exception("Cannot write to {$fullFilePath}");
		}

		fputcsv($fh, array_values($errMessage), ",", "\"", "");
		fclose($fh);
		return true;
	}

	protected function composeErrorMessage($level, $message, $context, $stacktrace, $idUser, $addTime, $logSession)
	{
		$ret = [];
		$ret['level'] = $level;
		$ret['message'] = $message;
		$ret['idUser'] = $idUser;
		$ret['addTime'] = $addTime;
		$ret['logSession'] = $logSession;

		foreach ($this->fileHeader as $contextItem) {
			$ret[$contextItem] = (isset($context[$contextItem])?$context[$contextItem]:'');
			unset($context[$contextItem]);
		}

		#$ret['stacktrace'] = $this->composeStacktrace($stacktrace);	// this seems useless for now
		$ret['context'] = ($context?json_encode($context, true): '');

		return $ret;
	}
}
