<?php
namespace Entity;

class GalileoService extends \App\Entity\GDSServiceAbstract
{
	/**
	 * The sistem code from the importedOrders
	 * @var string
	 */
	const systemCode = 'galileo';

	/**
	 * @param String $idFile
	 * @return \App\Entity\GeneralAbstract
	 */
	protected function getFile($idFile)
	{
		return \Entity\GalileoFile::select($idFile);
	}

	/**
	 * @return \App\Galileo\Storage\StorageHandler
	 */
	public function getStorageObjInstance()
	{
		return \App\Galileo\Storage\StorageHandler::getInstance();
	}

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

	/**
	 * Returns the corresponding field of the selected entity
	 *
	 * @param String $var
	 * @return Mixed
	 */
	protected function getAttribute($var)
	{
		// CHECK EVERY POSSIBLE VALUES THAT $var MAY HAVE -----------------------------------------
		switch ($var) {
			case 'TINABookUser':
				return User::select($this->fields['idTINABookUser']);

			case 'TINAIssueUser':
				return User::select($this->fields['idTINAIssueUser']);

			// return the first service that got inserted for this whole PNR
			case 'PNRRootService':
				if (!array_key_exists($var, $this->fields)) {
					$this->fields[$var] = $this->getAttribute_PNRRootService_using_references();
				}

				return $this->fields[$var];

			case 'PNRFiles':
				$ret = [];
				$references = $this->getAllRelatedReferences();
				foreach ($references as $refId) {
					$ret[self::select($refId)->idFile] = $this->getFile(self::select($refId)->idFile);
				}

				return array_values($ret);

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


	/**
	 * Sets the corresponding field of the inserting/updating entity
	 *
	 * @param String $var
	 * @return Mixed
	 */
	protected function setAttribute($var, $value)
	{
		// CHECK EACH POSSIBLE FIELD VALUE --------------------------------------------------------
		switch ($var) {
			case 'transactionCode':

			case 'idGalileoBookUser':
			case 'idGalileoIssueUser':
			case 'idGalileoBookOffice':
			case 'idGalileoIssueOffice':
			case 'idTINABookUser':
			case 'idTINAIssueUser':
			case 'idTINABookOffice':
			case 'idTINAIssueOffice':
			{
				$this->fields[$var] = $value;
				break;
			}

			// the field is not valid
			default: {
				return parent::setAttribute($var, $value);
			}
		}
	}
}
