<?php

namespace App\Logger;


class TINALogger extends \Engine\Logger\GeneralAbstract
{

	/**
	 * Force a custom log file path
	 */
	private $fullFilePath = null;

	private $DBLogger = null;

	private $diskLogger = null;


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

		$this->DBLogger = new \Engine\Logger\Db();
		$this->DBLogger->setLogSession($this->logSession);
	}

	/**
	 * Set custom log file path
	 */
	public function setFullFilePath($fullFilePath)
	{
		$this->fullFilePath = $fullFilePath;

		if ($this->diskLogger) {
			$this->diskLogger->setFullFilePath($this->fullFilePath);
		}
	}

	/**
	 * Get custom log file path
	 */
	public function getFullFilePath()
	{
		return $this->fullFilePath;
	}

	/**
	 * Try saving the error in database with DBLogger
	 * If it fails, save error in file with FileLogger
	 * (non-PHPdoc)
	 * @see \Engine\Logger\GeneralAbstract::logMessage()
	 */
	public function writeRawMessage($fields)
	{

		if (!array_key_exists('source', $fields) or !$fields['source']) {
			$fields['source'] = 'TINALogger';
		}

		try {
			$this->DBLogger->writeRawMessage($fields);
			return 'DBLogger';
		}
		catch (\RuntimeException $ex) {
			if (!$this->diskLogger) {
				$this->diskLogger = new \Engine\Logger\DbEmulated();

				if ($this->fullFilePath) {
					$this->diskLogger->setFullFilePath($this->fullFilePath);
				}

				$this->diskLogger->setLogSession($this->logSession);

				$this->diskLogger->critical(sprintf("Cannot write log messages to database. Exception: %s", $ex->getMessage()), [
					'exception' => $ex,
				]);
			}

			$this->diskLogger->writeRawMessage($fields);
			return 'diskLogger';
		}
	}
}
