<?php
namespace Modules\Admin\FluxInstances;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing
{
	/**
	 * Indicates if the entity execution should use or not a transaction. It left to 'null' the
	 * class won't work correctly - the concrete class must set it to true/false.
	 * @var Boolean
	 */
	protected $useSqlTransaction = true;

	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = ['name', 'addTime', 'lastHeartbeat'];

	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['insert'] = 				['checkOption' => false, ];
		$this->actionsCfg['update'] = 				['checkOption' => false, ];
		$this->actionsCfg['delete'] = 				['checkOption' => false, ];
		$this->actionsCfg['sendAuthenticate'] = 	['checkOption' => false, ];
		$this->actionsCfg['sendApplicationLogs'] = 	['checkOption' => false, ];
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::actionInsert()
	 */
	protected function actionInsert($R)
	{
		global $P;

		//  determine system type
		$type = '';
		$model = new \Modules\Admin\FluxInstances\Model();
		$system = $model->getSystem($R['assignedSystem']);
		if ($system and $system->isImporter) {
			$type = 'importer';
		}
		if ($system and $system->isExporter) {
			$type = 'exporter';
		}

		foreach (['basePath', 'confirmedPath', 'ignoredFiles'] as $key) {
			if (array_key_exists($key, (array)$P[$type])) {
				$R[$key] = 	$P[$type][$key];
			}
		}

		foreach (['createMonthBasedFolders', 'createMonthBasedFoldersOnServer', 'behaviourOnInvalidFile', 'filesSortMethod', 'behaviourOnSystemLoad', 'behaviourOnIdle', ] as $key) {
			if (array_key_exists($key, (array)$R[$type])) {
				$R[$key] = 	$R[$type][$key];
			}
		}

		return parent::actionInsert($R);
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_getDefaultFormData()
	 */
	protected function insert_getDefaultFormData($R)
	{
		$formData = [];

		if (!$R['appToken']) {
			$formData['appToken'] = \Engine\RandomGenerator::randomString(mt_rand(32, 40));
		}

		$formData['importer']['ignoredFiles'] = [
			'Thumbs.db',
			'Desktop.ini',
		];

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::insert_createEntityObject()
	 */
	protected function insert_createEntityObject($formData)
	{
		$entityObj = \Entity\FluxInstance::insert();
		$entityObj->name 					= $formData['name'];
		$entityObj->appToken 				= $formData['appToken'];
		$entityObj->filesSortMethod 		= (string)$formData['filesSortMethod'];
		$entityObj->disabled 				= (bool)$formData['disabled'];
		$entityObj->requestToken 			= null;
		$entityObj->lastHeartbeat 			= null;
		$entityObj->assignedSystem 			= $formData['assignedSystem'];
		$entityObj->basePath 				= trim((string)$formData['basePath']);
		$entityObj->confirmedPath 			= trim((string)$formData['confirmedPath']);
		$entityObj->behaviourOnInvalidFile 	= $formData['behaviourOnInvalidFile'];
		$entityObj->createMonthBasedFolders = (string)$formData['createMonthBasedFolders'];
		$entityObj->createMonthBasedFoldersOnServer= (string)$formData['createMonthBasedFoldersOnServer'];
		$entityObj->ignoredFiles 			= array_filter((array)$formData['ignoredFiles']);
		$entityObj->behaviourOnSystemLoad 	= (string)$formData['behaviourOnSystemLoad'];
		$entityObj->behaviourOnIdle 		= (string)$formData['behaviourOnIdle'];
		$entityObj->sendInvalidFileEmail 	= array_filter((array)$formData['sendInvalidFileEmail']);
		return $entityObj;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::actionUpdate()
	 */
	protected function actionUpdate($R)
	{
		global $P;

		//  determine system type
		$type = '';
		$model = new \Modules\Admin\FluxInstances\Model();
		$system = $model->getSystem($R['assignedSystem']);
		if ($system and $system->isImporter) {
			$type = 'importer';
		}
		if ($system and $system->isExporter) {
			$type = 'exporter';
		}

		foreach (['basePath', 'confirmedPath', 'ignoredFiles', ] as $key) {
			if (array_key_exists($key, (array)$P[$type])) {
				$R[$key] = 	$P[$type][$key];
			}
		}

		foreach (['createMonthBasedFolders', 'createMonthBasedFoldersOnServer', 'behaviourOnInvalidFile', 'filesSortMethod', 'behaviourOnSystemLoad', 'behaviourOnIdle', ] as $key) {
			if (array_key_exists($key, (array)$R[$type])) {
				$R[$key] = 	$R[$type][$key];
			}
		}

		return parent::actionUpdate($R);
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::update_getDefaultFormData()
	 */
	protected function update_getDefaultFormData($idEntity)
	{
		// select entity city
		$entityObj = \Entity\FluxInstance::select($idEntity);
		if (!$entityObj->recordExists()) {
			return null;
		}

		$type = '';
		$model = new \Modules\Admin\FluxInstances\Model();
		$system = $model->getSystem($entityObj->assignedSystem);
		if ($system and $system->isImporter) {
			$type = 'importer';
		}
		if ($system and $system->isExporter) {
			$type = 'exporter';
		}

		$formData = [];
		$formData['name'] 		= 							$entityObj->name;
		$formData['appToken'] 	= 							$entityObj->appToken;
		$formData['disabled'] 	= 							(bool)$entityObj->disabled;
		$formData['sendInvalidFileEmail'] = 				$entityObj->sendInvalidFileEmail;
		$formData[$type]['basePath'] 	= 					$entityObj->basePath;
		$formData[$type]['confirmedPath'] 	= 				$entityObj->confirmedPath;
		$formData[$type]['ignoredFiles'] = 					$entityObj->ignoredFiles;
		$formData[$type]['behaviourOnInvalidFile'] = 		$entityObj->behaviourOnInvalidFile;
		$formData[$type]['createMonthBasedFolders'] = 		$entityObj->createMonthBasedFolders;
		$formData[$type]['filesSortMethod'] = 				$entityObj->filesSortMethod;
		$formData[$type]['createMonthBasedFoldersOnServer']=$entityObj->createMonthBasedFoldersOnServer;
		$formData[$type]['behaviourOnSystemLoad'] = 		$entityObj->behaviourOnSystemLoad;
		$formData[$type]['behaviourOnIdle'] = 				$entityObj->behaviourOnIdle;
		$formData['assignedSystem'] = 						$entityObj->assignedSystem;

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_createEntityObject($formData)
	{
		$entityObj = \Entity\FluxInstance::update($formData['id']);
		$entityObj->name 							= $formData['name'];
		$entityObj->disabled 						= (bool)$formData['disabled'];
		$entityObj->assignedSystem 					= $formData['assignedSystem'];
		$entityObj->basePath 						= trim((string)$formData['basePath']);
		$entityObj->confirmedPath 					= trim((string)$formData['confirmedPath']);
		$entityObj->behaviourOnInvalidFile 			= $formData['behaviourOnInvalidFile'];
		$entityObj->createMonthBasedFolders 		= $formData['createMonthBasedFolders'];
		$entityObj->createMonthBasedFoldersOnServer = $formData['createMonthBasedFoldersOnServer'];
		$entityObj->filesSortMethod 				= $formData['filesSortMethod'];
		$entityObj->ignoredFiles 					= array_filter((array)$formData['ignoredFiles']);
		$entityObj->sendInvalidFileEmail 			= array_filter((array)$formData['sendInvalidFileEmail']);
		$entityObj->behaviourOnSystemLoad 			= $formData['behaviourOnSystemLoad'];
		$entityObj->behaviourOnIdle 				= $formData['behaviourOnIdle'];

		return $entityObj;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::delete_createEntityObject()
	 */
	protected function delete_createEntityObject($idRecord)
	{
		return \Entity\FluxInstance::delete($idRecord);
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionDefineParams()
	 */
	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		switch ($option->getId()) {
			case 'insert':
				$option->determineOperationAvailability(\Entity\FluxInstance::insert());
			break;

			case 'update':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\FluxInstance::update($selectedItem))) {
						break;
					}
				}
			break;

			case 'delete':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\FluxInstance::delete($selectedItem))) {
						break;
					}
				}
			break;

			case 'sendAuthenticate':
			case 'sendApplicationLogs':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\FluxInstance::update($selectedItem))) {
						break;
					}
				}
			break;
		}

		return true;
	}

	protected function bulkActionSendAuthenticate(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		foreach ($recordsIds as $id) {
			\Entity\FluxInstance::insertIntoCommandQueue($id, [
				'action' => 'Authenticate',
				'params' => [],
			]);

			$msgs->addSuccess($this->lang['sendAuthenticate']['messages']['successMessage']);
		}
		$msgs->groupMessagesByTypeAndText();
	}

	protected function bulkActionSendApplicationLogs(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		foreach ($recordsIds as $id) {
			\Entity\FluxInstance::insertIntoCommandQueue($id, [
				'action' => 'SendApplicationLogs',
				'params' => [],
			]);

			$msgs->addSuccess($this->lang['sendApplicationLogs']['messages']['successMessage']);
		}
		$msgs->groupMessagesByTypeAndText();
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return \Entity\FluxInstance::select($id)->name;
	}
}
