<?php

namespace Modules\Admin\CurrencyExchange\CheckOnlineSystem;

/**
 * This module is used for processing multiple services at once.
 */
class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\PopupAbstract::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['index'] = [ 'checkSection' => 'Modules/Admin/CurrencyExchange', 'checkOption' => false ];
	}


	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		if (count($CFG['currencies']['markets']) == 1) {
			$market = $CFG['currencies']['markets'][0];
			$formData = [];

			if ($CFG['currencies']['autoUpdateCurrencyExchange'][$market]) {
				$formData['stats'] = [];

				foreach($CFG['currencies']['autoUpdateCurrencyExchange'][$market] as $currencyType => $systemCode) {

					$formData['stats'][$currencyType]['systemCode'] = $systemCode;

					$startTime = microtime(true);

					try {
						$sysLoaderObj = new \App\CurrencyExchange\System_Load($systemCode);
						$sysObj = $sysLoaderObj->getSystemObject();
						$rates = $sysObj->getRates();

						$formData['stats'][$currencyType]['online'] = true;
						$formData['stats'][$currencyType]['rates'] = $rates;
						if (!$rates) {
							$formData['stats'][$currencyType]['error'] = $this->lang['index']['fields']['noRates'];
						}


					} catch (\App\CurrencyExchange\Exception $e) {
						$formData['stats'][$currencyType]['online'] = false;
						$formData['stats'][$currencyType]['error'] = $e->getMessage();
					}

					$endTime = microtime(true);
					$formData['stats'][$currencyType]['checkDuration'] = round($endTime-$startTime, 4);
				}
			}
		}
		return $formData;
	}

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