<?php
namespace App\Sabre\LineParser\Types\Line;

/**
 *
 * @author Lucian Sirbu
 */
class M6 extends \App\Sabre\LineParser\Types\SabreBaseLine
{
	/**
	 * M6 – Passenger Fare Calculation Data Record
	 * Fare Calculation data is built for each different passenger type that is ticketed. This record data will
	 * only be present if the IUR record was created as a result of a ticketing transaction. Each Fare Calculation
	 * item will be followed by a Carriage Return. There is a maximum of 99 fare calculation items. The
	 * maximum length of each fare calculation item is variable. The count of the total number of calculation
	 * items is found in the M0 field label “IU0NM6”.
	 */

	/**
	 * Children elements
	 */
	protected $children = [
	    ['key'=>'IU6MID',    'type'=>'Constant',      'len'=>2,       'val'=>'M6',    'label'=>'IU6MID'],    // MESSAGE ID - "M6"
	    ['key'=>'IU6RTY',    'type'=>'StringTrim',    'len'=>3,                       'label'=>'IU6RTY'],    // RECORD/PASSENGER TYPE
		['key'=>'IU6FCT',    'type'=>'StringTrim',    'len'=>1,    'req'=>false,      'label'=>'IU6FCT'],    // FARE CALCULATION TYPE
		['key'=>'IU6CPR',    'type'=>'StringTrim',    'len'=>1,    'req'=>false,      'label'=>'IU6CPR'],    // COMPRESS PRINT INDICATOR
		['key'=>'IU6FC12',   'type'=>'StringRTrim',                'req'=>false,      'label'=>'IU6FC12'],   // VARIABLE FARE CALCULATION DATA
	    ['key'=>'NL',        'type'=>'NewLine',],
	];

	/**
	 * {@inheritDoc}
	 * @see \App\Utils\BaseParser\TextParser\BlockAbstract::postExtract()
	 */
	protected function postExtract(\App\Utils\BaseParser\TextParser\ExtractedBlock $ret)
	{
		// interpret fare calculation data, when we have a linear format, not compresset
		$ret->extractedData['IU6FC12_'] = [
			'unknownFormat' => true,
		];

		$ret->extractedData['IU6RTY_'] = (new \App\Utils\BaseParser\Utils\PassengerTypeParser())->loadTypesFromPreset('travelport')->match($ret->extractedData['IU6RTY']);

		if ($ret->extractedData['IU6RTY'] && $ret->extractedData['IU6FCT']==1 && !$ret->extractedData['IU6CPR']) {
			$fareCalculationExtractorObject = \App\Utils\BaseParser\Utils\FareCalculationExtractor::getInstance();
			try {
				$ret->extractedData['IU6FC12_'] = $fareCalculationExtractorObject->extract($ret->extractedData['IU6FC12']);
			}
			catch (\App\Utils\BaseParser\TextParser\Exception\LineParser $ex) {
				$ret->extractedData['IU6FC12_'] = [
					'unknownFormat' => 	true,
					'error' => 			true,
					'message' => 		$ex->getMessage(),
				];
			}
		}

		return $ret;
	}
}
