<?php
namespace Entity;

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

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

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

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

	/**
	 * 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 'idWorldspanBookUser':
			case 'idWorldspanIssueUser':
			case 'idWorldspanBookOffice':
			case 'idWorldspanIssueOffice':
			case 'idTINABookUser':
			case 'idTINAIssueUser':
			case 'idTINABookOffice':
			case 'idTINAIssueOffice':
			{
				$this->fields[$var] = $value;
				break;
			}

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