<?php

namespace App\Form\Input;

/**
 * Supplier and product autocomplete field
 *
 */
class Autocomplete_SupplierAndProduct extends Autocomplete_GeneralAbstract
{

	protected $class = "autocomplete";

	/**
	 * The constructor for the suppliers autocomplete
	 *
	 * @param String $label
	 * @param String $name
	 * @param Array $value
	 */
	public function __construct($label=null, $name=null, $value=null)
	{
		parent::__construct($label, $name, $value);
		$this->url = \Engine\Mvc\Dispatcher::getInstance()->getAppUrl('Modules/RemoteData/AutocompleteFieldData', '', ['class'=>'SupplierAndProduct']);
		$this->setStyle('minimumTextLength', 2);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\Autocomplete::getValue()
	 */
	public function getValue()
	{
		$v = parent::getValue();
		if ($v==='|') {
			$v = '';
		}
		return $v;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\Autocomplete::getTemplateParams()
	 */
	protected function getTemplateParams($templateClass = null, $parentElement = null)
	{
		$params = parent::getTemplateParams($templateClass, $parentElement );

		// fill in the user name (if not manually set)
		if ($this->value and !$this->displayValue) {
			list($idSupplier, $idSupplierProduct)=explode('|', $this->value);
			if ($idSupplierProduct) {
				$this->displayValue=\Entity\SupplierProduct::select($idSupplierProduct)->name;
			} else {
				$this->displayValue=\Entity\Supplier::select($idSupplier)->name;
			}
			$params['displayValue']=$this->displayValue;
		}

		return $params;

	}

}

