<?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 sly_Controller_Userautocomplete extends sly_Controller_Ajax implements sly_Controller_Interface {
	public function autocompleteAction() {
		$response   = sly_Core::getResponse();
		$name       = strtolower(sly_get('name', 'string'));
		$dispatcher = sly_Core::dispatcher();
		$result     = $dispatcher->filter('WV_USERAUTOCOMPLETE', $name);

		if (is_array($result)) {
			$values = array();
			foreach ($result as $id => $name) $values[] = $name . '|' . $id;
		}
		else {
			$sql = WV_SQL::getInstance();
			$sql->query('SELECT id,name FROM ~user WHERE LOWER(name) LIKE ? ORDER BY name', "$name%", '~');

			$values = array();
			foreach ($sql as $row) $values[] = sprintf('%s|%d', $row['name'], $row['id']);
		}

		$response->setContentType('text/plain');
		$response->setContent(implode("\n", $values));

		return $response;
	}

	public function checkPermission($action) {
		sly_Util_Session::start();
		return sly_Util_User::getCurrentUser() !== null;
	}
}
