<?php
namespace App\Cron\Job;

/**
 * The class automatically import currency exchange rates (it must run daily); if there are
 * currency types that must be defined manually, the rates may be imported from the previous
 * date (if configured so).
 * @author Gabriel
 */
class ImportCurrencyExchangeRates extends \App\Cron\Job\Utils\GeneralAbstract
{
	/**
	 * Cronjob category: {system|operational|financial|reporting}
	 * @var string
	 */
	protected $category = 'financial';

	public function __construct()
	{
		parent::__construct();

		$this->options['StopAndRestartJob']['maxRestarts'] = 10;	// 10 restarts
		$this->options['StopAndRestartJob']['maxDurationOfRestarts'] = 10*60;	// 10 mins
	}

	/**
	 * The method returns the form which is needed for the the current cronjob settings saving.
	 */
	public function getSettingsDialog(array $fields)
	{
		$form = parent::getSettingsDialog($fields);

		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();
		$lang = \App\Loader_Lang::getInstance()->getSection("Admin/CronJobs/Management/ImportCurrencyExchangeRates");

		$formContainer = \Engine\Form\Container\Fieldset::create($_LANG['Admin']['CronJobs']['Management']['formFields']['legend']);

		$form->addContainer($formContainer);

		$fld=new \Engine\Form\Input\Checkbox($lang['formFields']['importPrevDate'], 'allowCopyingFromPreviousDate', $fields['settings']['allowCopyingFromPreviousDate']);
		$fld->setTooltip($lang['formFields']['importPrevDateTooltip']);
		$formContainer->addElement($fld);

		$formContainer->groupInputsInArray("settings");

		return $form;

	}


	/**
	 * {@inheritDoc}
	 * @see \App\Cron\Job\Utils\GeneralAbstract::validateSettings()
	 */
	public function validateSettings(\App\Entity\Messages $msgs, array $fields)
	{
		if (!$fields['errorManagement'] or !count($fields['errorManagement']['email'])) {
			$msgs->addWarningText("The on-error email is mandatory.");
		}
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Cron\Job\Utils\GeneralAbstract::executeJob()
	 */
	protected function executeJob()
	{

		// the date which will be updated
		$updatingDate = TODAY_ISO;

		// check if the rates are already defined for the selected date
		$lastDefinedDate = \App\CurrencyExchange\Date::getInstance($updatingDate)->getLastDefinedDate();
		if ($lastDefinedDate==$updatingDate) {
			$this->logger->warning(sprintf('The currency exchange rates are already defined for this date `%s`', $updatingDate));
			return true;
		}

		// UPDATE THE CURRENCY EXCHANGE RATE IN THE DATABASE //////////////////////////////////////
		try {

			\DB::startTransaction();

			$currenciesMngObj = new \App\CurrencyExchange\Admin($updatingDate);

			// load rates from the previous date - only if set to do so
			if ($this->settings['allowCopyingFromPreviousDate']) {
				$this->logger->info('The process is configured to get previously inputted rates for currency types that cannot be imported automatically.');
				$currenciesMngObj->addRates_previousDate();
			} else {
				$this->logger->info('The process is configured to NOT get previously inputted rates for currency types that cannot be imported automatically. If there are missing exchange rates the process will not finish successfully.');
			}
			// load from external systems (after the prevDate rates might have been imported)
			$currenciesMngObj->addRates_externalSystems($updatingDate);

			// save in the db
			$currenciesMngObj->save();

			\DB::commitTransaction();

			$this->logger->success('The currency exchange rates were successfully imported and saved.');

		} catch (\App\MessagesException $e) {

			\DB::rollbackTransaction();

			$this->logger->error('The currency exchange rates could not be imported due to the following message(s):');

			$this->importFromMessageCollector($e->getMessagesCollector());

			// force a retry
			throw new \Exception\CronJob\StopAndRestartJob('Could not import the currency exchange rates. Retrying in 1 minute.');

		}

	}



}