package jdbc;

import java.util.HashSet;

@Exercice(5)
public class Query {
	private HashSet<String> fields=new HashSet<String>();
	private HashSet<String> tables=new HashSet<String>();
	private HashSet<String> constraints=new HashSet<String>();
	
	private void fillTable(String field){
		int i=field.indexOf('.');
		if (i==field.length()) throw new UnsupportedOperationException();
		String table=field.substring(0, i);
		tables.add(table);		
	}
	
	public Query select(String field){
		fields.add(field);
		fillTable(field);
		return this;
	}
	
	private Query where(String field, Object fieldOrConstant,String op){
		fillTable(field);
		if(fieldOrConstant instanceof String)
		try{
			fillTable((String)fieldOrConstant);
		}catch(UnsupportedOperationException e){}
		constraints.add(field+" "+op+" "+fieldOrConstant);
		return this;
	}
	
	public Query whereEqual(String field, Object fieldOrConstant){
		return where(field,fieldOrConstant,"=");
	}
	
	public Query whereDifferent(String field, Object fieldOrConstant){
		return where(field,fieldOrConstant,"<>");
	}

	public Query whereSmaller(String field, Object fieldOrConstant){
		return where(field,fieldOrConstant,"<");
	}

	public Query whereGreater(String field, Object fieldOrConstant){
		return where(field,fieldOrConstant,">");
	}

	public String toSQL(){
		StringBuffer sb=new StringBuffer("SELECT ");
		boolean test=false;
		for(String field : fields){
			if(test) sb.append(',');
			sb.append(field);
			test=true;
		}
		sb.append(" FROM ");
		test=false;
		for(String table : tables){
			if(test) sb.append(',');
			sb.append(table);
			test=true;
		}
		test=false;
		for(String constraint : constraints){
			if(test)
				sb.append(" AND ");
			else
				sb.append(" WHERE ");
			sb.append(constraint);
			test=true;
		}
		return sb.toString();
	}
	
}
