<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV_Form_User extends sly_Form_Input_Text {
	/**
	 * Renders the element
	 *
	 * This method renders the element.
	 *
	 * @return string  the XHTML code
	 */
	public function render() {
		$layout = sly_Core::getLayout();
		$base   = sly_Util_AddOn::assetBaseUri('webvariants/developer-utils');

		$layout->addJavaScriptFile($base.'js/jquery.autocomplete.min.js');
		$layout->addJavaScriptFile($base.'js/jquery.userautocomplete.js');

		$this->attributes['class']       = 'user_autocomplete';
		$this->attributes['value']       = $this->getDisplayValue();
		$this->attributes['placeholder'] = $this->placeholder;

		$value    = $this->getValue();
		$user     = sly_Util_User::findById($value);
		$username = $user instanceof sly_Model_User ? $user->getName() : '';

		$attributeString = $this->getAttributeString();
		return '<input type="hidden"'.(isset($this->attributes['data-origname']) ? ' data-origname="'.$this->attributes['data-origname'] : '').'" name="'.$this->getName().'" value="'.$value.'" /><input '.$attributeString.' value="'.$username.'" autocomplete="off"/>'.($this->annotation ? ' '.$this->annotation : '');
	}

	/**
	 * Returns the attributes as a HTML string
	 *
	 * @param  array $exclude  list of attribute names to exclude
	 * @return string          string like 'foo="bar" name="sly"'
	 */
	protected function getAttributeString($exclude = array()) {
		$exclude    = sly_makeArray($exclude);
		$attributes = array();

		foreach ($this->attributes as $name => &$value) {
			if (in_array($name, array('name', 'value', 'data-origname'))) continue;

			if (!is_array($value) && strlen($value) > 0 && !in_array($name, $exclude)) {
				$attributes[] = $name.'="'.sly_html($value).'"';
			}
		}

		return implode(' ', $attributes);
	}
}
