<?php

namespace Modules\Admin\AutoProcessRules\Execute;

/**
 * This section is used for opening a popup that will exwecute a rule.
 */
class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		return $R;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(array $R, \App\MessagesCollector $msgs)
	{

		$idRule = $R['id'];

		$idExecution = uniqid();
		$ruleLogs = new \App\AutoProcessRules\Logs\Rule($idExecution, $idRule);
		$OK = true;

		// become super user to ignore all user accesses during rules exec
		\App\UserAccess\CurrentUserAccessFast::getInstance()->becomeSuperUser();

		try {
			$ruleExec = \Entity\AutoProcessRule::execute($idRule);
			$ruleExec->ruleLogs = $ruleLogs;
			$ruleExec->save();
			$msgs->addSuccess($this->lang['index']['msgs']['ok']);
		} catch (\App\Entity\Exception $e) {
			$msgs->appendMessages( $e->getMessagesCollector() );
			$OK = false;
		} finally {
			// become super user to ignore all user accesses during rules exec
			\App\UserAccess\CurrentUserAccessFast::getInstance()->becomeNormalUser();
			// wruite logs
			$writeLogs = new \App\AutoProcessRules\Logs\WriteLogs($ruleLogs);
			$writeLogs->write();
		}

		return $OK;

	}

	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{

		$view->getMessagesCollector()->addWarning($this->lang['index']['msgs']['info']);

	}

}