<?php
namespace Entity;

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

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

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

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

	/**
	 * 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_transactionCode();
				}

				return $this->fields[$var];
			break;

			case 'RECLOC':
				return substr($this->getAttribute('transactionCode'), 0, 6);

			case 'PNRFiles':
				$ret = [];
				if ($this->getAttribute('RECLOC')) {
					$PNRServices = $this->getStorageObjInstance()->selectServiceArrFromDB([
						'transactionCode~'=>	$this->getAttribute('RECLOC').'-%',
					]);

					foreach ($PNRServices as $ref) {
						$ret[$ref['idFile']] = $this->getFile($ref['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 'idSabreBookUser':
			case 'idSabreIssueUser':
			case 'idSabreBookOffice':
			case 'idSabreIssueOffice':
			case 'idTINABookUser':
			case 'idTINAIssueUser':
			case 'idTINABookOffice':
			case 'idTINAIssueOffice':
			{
				$this->fields[$var] = $value;
				break;
			}

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