<?php
namespace Entity;

class FluxInstance extends \App\Entity\GeneralAbstract
{
	/**
	 * Indicate if the operations available for the current entity must be done inside a transaction or not.
	 * @var Boolean
	 */
	protected $saveInsideTransaction = true;

	/**
	 * (non-PHPdoc)
	 * @see App\Entity.SelectAbstract::setTableName()
	 */
	protected function setTableName(): void
	{
		global $DBTFluxInstances;
		$this->tableName = $DBTFluxInstances;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Entity\SelectAbstract::getAttribute()
	 */
	protected function getAttribute($var)
	{
		// CHECK EVERY POSSIBLE VALUES THAT $var MAY HAVE -----------------------------------------
		switch ($var) {
			case 'ignoredFiles': case 'sendInvalidFileEmail': case 'fluxCommandQueue': {
				if (!is_array($this->fields[$var])) {
					if ($this->fields[$var]) {
						$this->fields[$var] = unserialize($this->fields[$var]);
					}
					else {
						$this->fields[$var] = [];
					}
				}
				return $this->fields[$var];
			}

			case 'addUser': {
				return \Entity\User::select($this->fields['idAddUser'], $this->selectForUpdate);
			}

			case 'updateUser': {
				return \Entity\User::select($this->fields['idUpdateUser'], $this->selectForUpdate);
			}

			// the rest of the fields (most of them are just copied)
			default: {
				return parent::getAttribute($var);
			}
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see App\Entity.GeneralAbstract::setAttribute()
	 */
	protected function setAttribute($var, $value)
	{
		// check that operation is okay
		if ($this->operation!='insert' and $this->operation!='update') {
			throw new \Exception('You can use __set magic method only with insert/update operation in `'.__CLASS__.'` class.');
		}

		// CHECK EACH POSSIBLE FIELD VALUE --------------------------------------------------------
		switch ($var) {
			// simple fields
			case 'disabled': case 'name': case 'appToken':
			case 'basePath': case 'confirmedPath': case 'behaviourOnInvalidFile': case 'ignoredFiles': case 'sendInvalidFileEmail':
			case 'createMonthBasedFolders': case 'createMonthBasedFoldersOnServer':
			case 'assignedSystem': case 'filesSortMethod': case 'behaviourOnSystemLoad': case 'behaviourOnIdle':
			case 'requestToken': case 'lastHeartbeat': {
				$this->fields[$var]=$value;
				break;
			}

			// the field is not valid
			default: {
				throw new \Exception("The field '$var' is not valid for the `".__CLASS__."` entity.");
			}
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Entity\GeneralAbstract::save_filterSaveData()
	 */
	protected function save_filterSaveData(Array $saveData)
	{
		if (isset($saveData['ignoredFiles'])) {
			$saveData['ignoredFiles'] = serialize($saveData['ignoredFiles']);
		}

		if (isset($saveData['sendInvalidFileEmail'])) {
			$saveData['sendInvalidFileEmail'] = serialize($saveData['sendInvalidFileEmail']);
		}

		return $saveData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Entity\GeneralAbstract::save_executeDelete()
	 */
	protected function save_executeDelete(Array $saveData)
	{

		// EXECUTE SQL ----------------------------------------------------------------------------
		$this->save_executeSql_delete($this->tableName, $this->tablePrimaryKey, $this->id);

		$this->messages->addSuccessCode('delete_ok');
	}

	static public function insertIntoCommandQueue($fluxInstanceId, array $command)
	{
		$fluxInstance = \Entity\FluxInstance::select($fluxInstanceId);
		$fluxCommandQueue = $fluxInstance->fluxCommandQueue;
		$fluxCommandQueue[]= $command;


		global $DBTFluxInstances;
		$db = \DB::getInstance();
		$updateSQL="UPDATE `{$DBTFluxInstances}` SET `fluxCommandQueue`=? WHERE `id`=?";
		$fieldValues = [];
		$fieldValues[]= serialize($fluxCommandQueue);
		$fieldValues[]= $fluxInstanceId;

		$dbEx = $db->Execute($updateSQL, $fieldValues);

		if (!$dbEx) {
			\Log::getInstance()->dbError(sprintf("[%s] Could not update entity %s in the database", __METHOD__, get_called_class()), [
				'values' => 			new \Engine\Logger\Context\ArrayAssoc($fluxCommandQueue),
				'fluxInstanceId' => 	$fluxInstanceId,
			]);
			throw new \DBException("Could not update `fluxCommandQueue`.");
		}

		// return the execution object
		return $dbEx;
	}
}
