/**
 * Association.java
 * Created May 23, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.search;

import static com.tandbergtv.watchpoint.search.HQLQuery.PERIOD;

/**
 * Represents an association between entities. This is typically used when two classes do not have
 * a direct 1-1 or 1-n relationship in the object model.
 * 
 * @author Sahil Verma
 */
public class Association extends SearchParameter {

	protected Tuple t1;
	
	protected Tuple t2;
	
	/**
	 * Creates an Association
	 * @param name
	 */
	protected Association(String name) {
		super(name);
	}
	
	/**
	 * Creates an Association
	 * 
	 * @param e1
	 * @param property1
	 * @param e2
	 * @param property2
	 */
	public Association(String name, Entity e1, String property1, Entity e2, String property2) {
		this(name);
		this.t1 = new Tuple(e1, property1);
		this.t2 = new Tuple(e2, property2);
	}
	
	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.search.SearchParameter#getPartialWhereClause()
	 */
	public String getPartialWhereClause() {
		Entity e1 = t1.entity;
		Entity e2 = t2.entity;
	
		String clause = e1.getCompleteAlias();
		
		if (t1.property != null)
			clause += PERIOD + t1.property;
		
		clause += " = " + e2.getCompleteAlias();
		
		if (t2.property != null)
			clause += PERIOD + t2.property;
		
		return clause; 
	}

	/**
	 * Inner class to keep track of an entity and the association property
	 */
	class Tuple {
		
		Entity entity;
		
		String property;
		
		Tuple (Entity entity, String property) {
			this.entity = entity;
			this.property = property;
		}
	}
}
