<?php

namespace App\AutoProcessRules\Logs;

/**
 * Output log of an auto-process rule execution.
 * @author Gabi
 */
class Log
{

	/**
	 * The transaction id (we will have multiple logs per transaction)
	 * @var string
	 */
	public $idTransaction;

	/**
	 * The current message type: warning, error, info, success.
	 * @var String
	 */
	public $messageType;

	/**
	 * The current message text.
	 * @var String
	 */
	public $messageText;

	/**
	 * The current entity.
	 * @var String
	 */
	public $entityType;

	/**
	 * The current entity id.
	 * @var Int
	 */
	public $idEntity;

	/**
	 * The current entity operation.
	 * @var String
	 */
	public $entityOperation;

	/**
	 * The current log time (unix microtime).
	 * @var Float
	 */
	public $time;

	/**
	 * Sets the message type/text.
	 * @param string $messageType
	 * @param string $messageText
	 */
	public function __construct($messageType, $messageText)
	{
		$this->setMessage($messageType, $messageText);
		$this->time = microtime(true);
	}

	/**
	 * Statically creates a new object of the current type.
	 * @param string $messageType
	 * @param string $messageText
	 * @return \App\AutoProcessRules\Logs\Log
	 */
	static public function create($messageType, $messageText)
	{
		return new self($messageType, $messageText);
	}

	/**
	 * Create from general purpose Message object.
	 * @param \App\Message $appMessage
	 * @return \App\AutoProcessRules\Logs\Log
	 */
	static public function createFromMessage(\App\Message $appMessage, $idTransaction=null)
	{
		$log = new self($appMessage->getType(), $appMessage->getTextWithField());
		$log->idTransaction = $idTransaction;
		return $log;
	}

	/**
	 * Sets the message details and validates the message type.
	 * @param string $messageType
	 * @param string $messageText
	 * @return \App\AutoProcessRules\Logs\Log
	 */
	public function setMessage($messageType, $messageText)
	{
		// check the
		if (!in_array($messageType, ['info', 'warning', 'error', 'success'])) {
			throw new \Exception('Invalid message type: '.$messageType.' for AP rule log.');
		}
		$this->messageType = $messageType;
		$this->messageText = $messageText;
		return $this;
	}

	/**
	 * Attaches the entity details.
	 * @param string $entityType
	 * @param int $idEntity
	 * @param string $entityOperation
	 * @return \App\AutoProcessRules\Logs\Log
	 */
	public function setEntityDetails($entityType, $idEntity, $entityOperation=null)
	{
		$this->entityType = $entityType;
		$this->idEntity = $idEntity;
		if ($entityOperation) {
			$this->entityOperation = $entityOperation;
		}
		return $this;
	}


	/**
	 * Attaches the transcation id.
	 * @param string $idTransaction
	 * @return \App\AutoProcessRules\Logs\Log
	 */
	public function setIdTransaction($idTransaction)
	{
		$this->idTransaction = $idTransaction;
		return $this;
	}

}
