<?php

namespace Modules\Orders\ServiceItinerary;

class View_Utils_FormAdmin extends \App\Mvc\View_Utils_FormAbstract
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\View_Utils_FormAbstract::getForm()
	 */
	public function getForm()
	{
		$form = \Engine\Form\General::create();
		//$form->setStyle('width', 300)->setStyle('labelWidth', 25);

		$matrix = $this->buildMatrix($form, $this->values);

		$form->addElement($matrix);

		// warning on the first screen if no chosen offer
		if (!$this->values['save'] && !\Entity\Service::select($this->values['idService'])->chosenOffer->recordExists()) {
			$form->addMessage('warning', $this->lang['messages']['noOffer']);
		}

		// submit button
		$form->addElement(new \Engine\Form\Input\Hidden('', $this->submitButtonName, 1));

		return $form;
	}


	/**
	 * Build matrix input
	 * @param \Engine\Form\General $form
	 * @param array $values
	 */
	private function buildMatrix(\Engine\Form\General $form, Array $values)
	{

		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		$matrix = new \Engine\Form\Input\Matrix();
		$matrix->setName('segments');
		$matrix->setValue($values['segments']);
		$matrix->setStyle('render_rowIndex', false);
		//$matrix->setStyle('startIndex', $this->output['currentPage'] * $this->output['resultsPerPage']);

		// setup storage & ajax requests
		$storageKey = sprintf("%s-%s-%s", str_replace('\\', '', __METHOD__), CURRENT_ID_USER, $values['idService']);

		// set matrix url
		$matrix->setUrl(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl($this->controller->getModule(), "generateSegmentRow", [
				'idSupplier' => \Entity\Service::select($values['idService'])->chosenOffer->idSupplier,
				'clonesCount' =>	1,
				'inputMatrixStorageId' =>	$storageKey,
		]));


		// add matrix row
		$row = new \Engine\Form\Input\Matrix\Row();
		$matrix->addRow($row);


		// add matrix columns
		$cell1 = new \Engine\Form\Input\Matrix\Cell("");
		//$cell1->setName('description');
		//$cell1->setStyle('width', '700');
		$row->addCell($cell1);

		//$cell1->addContainer($cell1Table = \Engine\Form\Container\Table::create());

		$fieldset = \Engine\Form\Container\Fieldset::create("Segment <span class='matrix-row-counter'></span>");
		//$fieldset->setCollapsible(true);  // TODO
		$cell1->addContainer($fieldset);

		$formColumns = new \Engine\Form\Container\Columns();
		$fieldset->addContainer($formColumns);


		// COLUMN 1
		$cell1Table = \Engine\Form\Container\Table::create();
		$formColumns->addContainer($cell1Table);
		$cell1Table->setStyle('width', 200);

		$cell1Table->addElement($fldDepCity = new \App\Form\Input\Autocomplete_CountryCityStation($this->lang['formFields']['departure'], 'departureCountryCityStation'));
		$fldDepCity->setStyle('buttons', false);
		$cell1Table->addElement(new \Engine\Form\Input\Datetime($this->lang['formFields']['departureDateTime'], 'departureDateTime'));
		$cell1Table->addElement($fldSupplier = new \App\Form\Input\Autocomplete_Supplier($this->lang['formFields']['supplier'], 'supplier'));
		$fldSupplier->setStyle('buttons', false);

		//$cell1Table->setStyle('noLabel', true);
		$cell1Table->addElement($fldDuration = new \Engine\Form\Input\Time($this->lang['formFields']['duration'], 'duration'));
		$fldDuration->setCustomHTML("<i>[H:m]</i>");
		$cell1Table->addElement(new \Engine\Form\Input\Text($this->lang['formFields']['seatNumber'], 'seatNumber'));
		$cell1Table->addElement($fldStopOver = new \Engine\Form\Input\Select($this->lang['formFields']['stopOverAllowed'], 'stopOverAllowed'));
		$fldStopOver->showDefaultOption();
		$fldStopOver->setDefaultOptionText($this->lang['itinerary']['choose']);
		$fldStopOver->setPossibleValues([
				'y' => $_LANG['yes'],
				'n' => $_LANG['no']
		]);
		$cell1Table->addElement(new \Engine\Form\Input\Text($this->lang['formFields']['fareBasis'], 'fareBasis'));
		$cell1Table->addElement(new \Engine\Form\Input\Text($this->lang['formFields']['terminalCheckIn'], 'terminalCheckIn'));
		$cell1Table->addElement(new \Engine\Form\Input\Text($this->lang['formFields']['baggageCode'], 'baggageCode'));


		// COLUMN 2
		$cell2Table = \Engine\Form\Container\Table::create();
		$formColumns->addContainer($cell2Table);
		$cell2Table->setStyle('width', 200);

		$cell2Table->addElement($fldDestCity = new \App\Form\Input\Autocomplete_CountryCityStation($this->lang['formFields']['arrival'], 'arrivalCountryCityStation'));
		$fldDestCity->setStyle('buttons', false);
		$cell2Table->addElement( new \Engine\Form\Input\Datetime($this->lang['formFields']['arrivalDateTime'], 'arrivalDateTime'));

		$fldDistance = new \Engine\Form\Input\ElementWithElements($this->lang['formFields']['distance'], 'distance');
		$fldDistance->setStyle('renderMode', 'inline');
		$fldDistance->addElement( new \Engine\Form\Input\Text(NULL, 'distanceValue'), 'main');
		$fldDistance->addElement($fldDistanceUnit = new \Engine\Form\Input\Select(NULL, 'distanceUnit'), 'post');
		$cell2Table->addElement($fldDistance);

		foreach ($this->cfg['itinerary']['units'] as $unit) {
			$fldDistanceUnit->setPossibleValue($unit, $this->lang['itinerary']['units'][$unit]);
		}
		$cell2Table->addElement( new \Engine\Form\Input\Text($this->lang['formFields']['transportNumber'], 'transportNumber'));
		$cell2Table->addElement( new \Engine\Form\Input\Text($this->lang['formFields']['transportUnit'], 'transportUnit'));
		$cell2Table->addElement($fldClassName = new \Engine\Form\Input\Select($this->lang['formFields']['serviceClassName'], 'serviceClassName'));
		$fldClassName->showDefaultOption();
		$fldClassName->setDefaultOptionText($this->lang['itinerary']['choose']);
		foreach ($CFG['travel']['transportSegmentClassNames'] as $cls) {
			$fldClassName->setPossibleValue($cls, $_LANG['flightClass'][$cls]);
		}
		$cell2Table->addElement( new \Engine\Form\Input\Text($this->lang['formFields']['serviceClassCode'], 'serviceClassCode'));
		$cell2Table->addElement( new \Engine\Form\Input\Text($this->lang['formFields']['terminalCheckOut'], 'terminalCheckOut'));
		$cell2Table->addElement( new \Engine\Form\Input\Text($this->lang['formFields']['mealCode'], 'mealCode'));
		$cell2Table->addElement( new \Engine\Form\Input\Text($this->lang['formFields']['mealDescription'], 'mealDescription'));

		$matrix->setRenderRowCallback(function(\Engine\Form\Input\Matrix\Row $row, $index, $value) {
			$row->traverseTreeForAllChilds(function($elm, $row, $params) use ($index) {
				if ($elm instanceof \Engine\Form\Container\Fieldset) {
					$elm->setLabel(sprintf("Segment <span class='matrix-row-counter'>%d</span>", $index));
				}
			});
		});

		// store matrix
		$matrix->setSaveHandler(function($matrix) use ($storageKey) {
			\Engine\Cache\General::getInstance('disk')->set($storageKey, $matrix, 8*60*60);
		});


		return $matrix;
	}


	/**
	 * Determine the current view's action
	 * @return string
	 */
	public function getViewAction()
	{
		$action = preg_replace("/^(View_)(.+)$/", "$2", stripClassNamespace(get_class($this)));
		$action[0] = strtolower($action[0]);
		return $action;
	}


}