<?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 WV2_Filter_SortableValue implements WV_IFilter {
	protected $metainfo;
	protected $type;
	protected $columnName;
	protected $tableAlias;

	public function __construct($metainfo, $metainfoType, $columnName, $tableAlias = null) {
		$this->metainfo   = $metainfo;
		$this->type       = (int) $metainfoType;
		$this->columnName = $columnName;
		$this->tableAlias = (string) $tableAlias;

		// Der Tabellen-Alias kann überschrieben werden (s.o.), um eine bessere
		// Performance des QueryCaches von MySQL zu ermöglichen. Sollte jedoch
		// keiner angegeben werden, generieren wir selbst einen zufälligen
		// 8stelligen Alias.

		if ($tableAlias === null) {
			$this->createTableAlias();
		}
	}

	protected function createTableAlias() {
		$this->tableAlias = '';

		for ($i = 0; $i < 8; ++$i) {
			$this->tableAlias .= chr(97 + rand(0, 25));
		}
	}

	public function getRequiredTables() {
		return array();
	}

	public function isValid() {
		return true;
	}

	public function __toString() {
		return $this->toSQL();
	}

	public function toSQL() {
		$prefix   = sly_Core::getTablePrefix();
		$alias    = '`'.$this->tableAlias.'`';
		$join     = array(
			 $alias.'.metainfo = "'.$this->metainfo.'"',
			 $alias.'.meta_type = '.$this->type
		);

		if ($this->type === WV2_Metainfo::TYPE_MEDIUM) {
			$join[] = $prefix.'file.id = '.$alias.'.object_id';
			$join[] = $alias.'.clang = '.WV_Sally::clang(); // this is just plain wrong
		}
		elseif ($this->type === WV2_Metainfo::TYPE_USER) {
			$join[] = $prefix.'user.id = '.$alias.'.object_id';
			$join[] = $alias.'.clang = '.WV_Sally::clang(); // this is just plain wrong
		}
		else {
			$join[] = $prefix.'article.id = '.$alias.'.object_id';
			$join[] = $prefix.'article.clang = '.$alias.'.clang';
		}

		return '('.implode(' AND ', $join).')';
	}

	public function getExtraColumns($tables) {
		return array('`'.$this->tableAlias.'`.`value` AS `'.$this->columnName.'`');
	}

	public function getExtraTables($tables) {
		return array(sly_Core::getTablePrefix().'wv2_meta '.$this->tableAlias);
	}

	public function getJoinCondition($table, $masterTable) {
		return false;
	}
}
