<?php

namespace Engine\Form\Input;

// NOTE: this input leaks LOTS of (browser-side) memory when called through AJAX, because it keeps recreating the clones, the function names, the elements with the same names, and kept referenced at all times

/**
 * base input Cloned Autocomplete class
 * @author Lucian
 */
class Cloned_Autocomplete extends Autocomplete // TODO: make it abstract?
{

	protected $class = "clonedAutocomplete";

	public function __construct($label=null, $name=null, $value=null)
	{
		parent::__construct($label, $name, $value);

		$this->settings['minItems'] = 1;
		$this->settings['showCounter'] = false;
		$this->settings['addLocation'] = 'bottom'; // (bottom, top)

		$this->settings['operations'] = [];
		$this->settings['operations']['add'] = true;
		$this->settings['operations']['remove'] = true;
		# $this->settings['operations']['default'] = true;
	}

	/**
	 * Set clone add location
	 * @param String $location
	 * @return \Engine\Form\Input\Cloned_Autocomplete
	 */
	public function setCloneAddLocation($location)
	{
		$this->settings['addLocation'] = $location;
		return $this;
	}

	/**
	 * @param Array $value
	 * @return \Engine\Form\Input\Cloned_Autocomplete
	 */
	public function setValue($value)
	{
		// this is the same as the basic setValue function, because i need to override the autocomplete's version
		if(!is_array($value)){
			$value = [];
		}

		$this->value = [];  // without resetting, the cloned autocomplete does not work properly in matrix (value is appended to previous values)
		foreach ($value as $v){
			$v['title'] = htmlUnclean($v['title']);

			$this->value[] = $v;
		}
		return $this;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\ElementAbstract::loadTranslations()
	 */
	protected function loadTranslations($templateClass = null)
	{
		parent::loadTranslations();

		\App\Loader_Lang::getInstance()->loadAppFile('_customLoad/formField/inputs/generalAutocomplete.lang.php');

	}

	public function getDisplayValue()
	{
		return '';
	}

	protected function getTemplateParams($templateClass = null, $parentElement = null)
	{

		$params = parent::getTemplateParams($templateClass, $parentElement );

		if (is_array($params['value'])) {
			foreach($params['value'] as $key=>$elem) {
				if ($elem['id'] and !strlen((string)$params['value'][$key]['title'])) {
					$params['value'][$key]['title'] = htmlUnclean( $this->determineDisplayValue($elem['id']) );
				}
			}
		}

		return $params;

	}


}
