<?php
namespace Modules\Admin\Config\Server\LoadLimits;

class Controller extends \App\Mvc\Controller\Form\WindowAbstract
{

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		return [
			'overload' =>	\App\Config\ServerLoadLimits::getInstance()->get('overload'),
			'idle' =>		\App\Config\ServerLoadLimits::getInstance()->get('idle'),
		];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $formData, \App\MessagesCollector $msgs)
	{
		$this->check($formData, $msgs);

		if (!$msgs->hasErrorOrWarning()) {
			try {
				$systemVarsObj = \App\Config\ServerLoadLimits::getAdmin();
				$systemVarsObj->set('overload',	$formData['overload']);
				$systemVarsObj->set('idle', 	$formData['idle']);
				$systemVarsObj->save();
				$msgs->addSuccess($this->lang['messages']['success']);
			} catch (\App\Config\MessageException $e) {
				$msgs->addError(sprintf($this->lang['messages']['error'], $e->getMessage()));
			}
		}
	}

	private function check(Array $formData,  \App\MessagesCollector $msgs)
	{
		if (($formData['overload'] and !$formData['idle']) or
			($formData['idle']) and !$formData['overload']) {
			$msgs->addError('You must set both limits.');
		}

		if ($formData['idle'] >= $formData['overload']) {
			$msgs->addError("The idle limit can't be bigger than the overload one.");
		}
	}

}