<?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_Filter_Subselect implements WV_IFilter {

	/**
	 * @var WV_IFilter
	 */
	protected $filter;
	protected $table;
	protected $primary_key;
	protected $alias;
	public static $alias_cnt = 0;

	/**
	 *
	 * @param string $table
	 * @param WV_IFilter $filter
	 * @param string $primary_key string or array of fields
	 * @param string $alias named alias, null for auto generated
	 */
	public function __construct($table, WV_IFilter $filter, $primary_key = 'id', $alias = null) {
		if ($alias === null) {
			$alias = 'wv_filter_subselect_' . (self::$alias_cnt++);
		}
		$this->table = $table;
		$this->filter = $filter;
		$this->primary_key = $primary_key;
		$this->alias = $alias;
	}

	public function getRequiredTables() {
		return $this->filter->getRequiredTables();
	}

	public function isValid() {
		return $this->filter->isValid();
	}

	public function toSQL() {
		if (!$this->filter instanceof WV_Filter_Interface_ChangeTable)
			throw new sly_Exception('all filters must implement WV_Filter_Interface_ChangeTable when using changeTable');

		$this->filter->changeTable($this->table, $this->alias);

		$a = array();
		$b = array();
		foreach ((array) $this->primary_key as $field) {
			$a[] = sprintf('%s%s.%s', sly_Core::getTablePrefix(), $this->table, $field);
			$b[] = sprintf('%s.%s',  $this->alias, $field);
		}

		return sprintf('(%s) IN (SELECT %s FROM %s%s %s WHERE %s)',
		implode(', ', $a), implode(', ', $b), sly_Core::getTablePrefix(), $this->table, $this->alias,
				$this->filter->toSQL());
	}

}
