package com.tandbergtv.watchpoint.search;

import com.tandbergtv.workflow.driver.search.SearchOperator;


/**
 * used to provide support for subselects
 * @author vaibhav
 *
 */
public class NestedQueryEntity extends Entity{

	/**
	 * constructor 
	 * @param name
	 * @param clazz
	 * @param alias
	 */
	public NestedQueryEntity(String name, Class<?> clazz, String alias) {
		super(name, clazz, alias);
	}

	
	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.search.Entity#getPartialWhereClause()
	 * 
	 * Is only supposed to use the NOT IN
	 */
	public String getPartialWhereClause() {
		com.tandbergtv.workflow.util.SearchCriteria crit = new com.tandbergtv.workflow.util.SearchCriteria();
		if(subparameters.size() > 1) 
			throw new RuntimeException("");

		for (SearchParameter subparameter : this.subparameters) {
			if (subparameter instanceof Entity) {
				crit.addParameter(subparameter);		
			} 
		}
		
		String s = QueryBuilder.newInstance().buildQuery(crit);

		return this.getCompleteAlias() + " " + getOperator().toString() + " (" + s + ")";
	}

	/**
	 * only use the nested entity's class name and alias. No need to go into
	 * subparameters
	 */
	public String getPartialFromClause(int count) {
		return this.clazz.getName() + " " + this.getCompleteAlias();
	}

	/**
	 * No need for a orderBy clause for nested entity
	 */
	public String getPartialOrderByClause() {
		return "";
	}
	
	public String getSelectClause() {
		throw new RuntimeException("Select Clause should never be created for this NestedQueryEntity");
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.search.SearchParameter#setOperator(com.tandbergtv.workflow.driver.search.SearchOperator)
	 */
	@Override
	public void setOperator(SearchOperator operator) {
		if (operator != SearchOperator.IN && operator != SearchOperator.NOTIN)
			throw new RuntimeException("Search operator is invalid: " + operator);
		super.setOperator(operator);
	}
}