<?php

namespace App\Cron\Job;

/**
 * The class will check that system date and time are correct, using NTP servers
 * @author Dan
 */
class ExportData extends \App\Cron\Job\Utils\ShortRunningCronJobAbstract
{
	/**
	 * Cronjob category: {system|operational|financial|reporting}
	 * @var string
	 */
	protected $category = 'financial';


	/**
	 * The default number of files to be processed at once (by default).
	 * @var Int
	 */
	private $defaultChunkSize = 10;

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

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

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

		$form->addContainer($formContainer);

		$fld = new \Engine\Form\Input\Text($_LANG['Admin']['CronJobs']['Management']['ExportData']['editOptions']['chunkSize'], 'chunkSize', $fields['settings']['chunkSize']);
		$fld->setMandatory();
		$fld->setValidatorParam('type', 'int');
		$fld->setTooltip($_LANG['Admin']['CronJobs']['Management']['ExportData']['editOptions']['chunkSizeInfo']);
		$formContainer->addElement($fld);

		$formContainer->groupInputsInArray("settings");

		return $form;
	}


	protected function executeJob()
	{
		if (!$this->settings['chunkSize']) {
			$this->logger->info(sprintf('No chunk size set - using the default value of %s files per execution.', $this->defaultChunkSize));
			$chunkSize = $this->defaultChunkSize;
		} else {
			$this->logger->info(sprintf('The cron was set to process %s file(s) per execution.', $this->settings['chunkSize']));
			$chunkSize = $this->settings['chunkSize'];
		}

		// execute the queue
		$queueManager = \App\ExportData\QueueManager::getInstance();
		$queueManager->process($chunkSize);

		// attach logs from queue manager
		$this->importFromMessageCollector($queueManager->getMessagesCollector());

		$this->logger->info('You should analyze the export data logs to see the details of the processed files.');

	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Cron\Job\Utils\GeneralAbstract::validateSettings()
	 */
	public function validateSettings(\App\Entity\Messages $msgs, array $fields)
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		// check if the cronjob chunk size is numeric
		if ($fields['settings'] && (!$fields['settings']['chunkSize'] || !is_numeric($fields['settings']['chunkSize']))) {
			$msgs->addWarningText($_LANG['Admin']['CronJobs']['Management']['ExportData']['field']['warning']['notificationEmails_invalid']);
			return false;
		}
	}
}
