<?php
namespace App\Amadeus\StructureParser\Structures\MCO;

class Itinerary extends \App\Amadeus\StructureParser\Parser\Itinerary
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Amadeus\StructureParser\Parser\Itinerary::isValid()
	 */
	public function isValid()
	{
		$parsedStructure = $this->transaction->getParsedStructure();
		$indexType = $this->transaction->getIndexType();
//		$index = $this->transaction->getIndex();

		if($indexType=='MCO'){
			if(isset($parsedStructure['MCO'])) {
				return true;
			}
		}

		return false;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Amadeus\StructureParser\Parser\Itinerary::updateInternalSegmentData()
	 */
	protected function updateInternalSegmentData()
	{
		$indexType = $this->transaction->getIndexType();

		if($indexType=='MCO'){
			$ret = $this->updateInternalSegmentData_MCO();
			if($ret){
				return $ret;
			}
		}

		return false;
	}

	/**
	 * Get data from specific line
	 * @return multitype:\App\Amadeus\StructureParser\Types\ItinerarySegment |NULL
	 */
	protected function updateInternalSegmentData_MCO()
	{
		$parsedStructure = $this->transaction->getParsedStructure();
		$index = $this->transaction->getIndex();

		$MCOt = $parsedStructure['MCO'][$index->MCO];
		$I = \App\Amadeus\StructureParser\Helpers::internal_MCO_MCO_to_I($parsedStructure, $MCOt, $this->transaction);

		foreach ($parsedStructure['MCO'] as $idx=>$MCO) {
			$add = false;
			if ($MCO && $idx==$index->MCO) {
				$add = true;
			}

			if ($add && $MCO['PSGASS']) {
				$add = false;
				foreach ($MCO['PSGASS'] as $PSGASS) {
					if ($PSGASS==(int)$I['PSGRNBR']) {
						$add = true;
						break;
					}
				}
			}

			if ($add) {
				$item = new \App\Amadeus\StructureParser\Types\ItinerarySegment();

				$item->departure->suggest('airport', 	$MCO['CITYCDE']);
				$item->departure->suggest('airport', 	$MCO['ATINFO']);

				// detect the departure airport/city/country
				$match = $item->match([
					'cityCode' => 		[$MCO['CITYCDE']],
					'airportCode' => 	[$MCO['CITYCDE']],
					'cityName' => 		[$MCO['ATINFO']],
					'airportName' => 	[$MCO['ATINFO']],
				], false);
				$item->departure->airportCode = 	$match->airport??null;
				$item->departure->cityId = 			$match->city??null;
				$item->departure->countryCode = 	$match->country??null;

				// detect departure/arrival dates & hours
				$item->departure->date = 		$MCO['DEPDATE'];

				// transport details
				$item->supplierCode = 			rtrim($MCO['AIRCDE']);
				$item->segmentType = 			$MCO['_type'];

				$this->itinerary->appendSegment($item);
			}
		}

		return null;
	}
}
