package com.tandbergtv.workflow.driver.search;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

/**
 * Holds information for a search predicate involving a range. 
 * 
 * @author Imran Naqvi
 */
public class RangeParameter extends SearchParameterBase {

	private String from = null;

	private String to = null;

	public RangeParameter(String name) {
		super(name);
	}

	public RangeParameter(String name, SearchType fieldType) {
		super(name, fieldType);
	}

	public RangeParameter(String name, SearchType fieldType, boolean varInstance) {
		super(name, fieldType, varInstance);
	}

	/**
	 * Creates a range parameter
	 * @param name
	 * @param from
	 */
	public RangeParameter(String name, SearchType fieldType, String from) {
		this(name, fieldType);
		this.from = from;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	@Override
	public String getPredicate() {
		if (this.getFieldType()==SearchType.STRING){
			if(from == null || from.equals(""))
				return " <= '" + to + "'";
			if(to == null || to.equals(""))
				return " >= '" + from + "'";
			return " between " + "'" + from + "' AND '" + to + "'";
		}
		if (this.getFieldType()==SearchType.DATE){
			if (from == null || from.equals(""))
				return " < to_date('" + getModifiedToDate() + "','" + DATE_FORMAT_BETTER_HQL + "' )";
			if (to == null || to.equals(""))
				return " >= to_date('" + from + "','" + DATE_FORMAT + "' )";
			return " between " + "to_date('" + from + "','" + DATE_FORMAT
					+ "' ) AND to_date('" + getModifiedToDate() + "','" + DATE_FORMAT_BETTER_HQL + "' )";
		}
		if(from == null || from.equals(""))
			return " <= " + to;
		if(to == null || to.equals(""))
			return " >= " + from;
		return " between " + from + " AND " + to;		
	}

	/**
	 * Adds one day to the to date since by default the date is set to
	 * 12am. So the 'to' date becomes exclusive when we search 
	 * between the from and to.
	 * @param toDate
	 */
	private String getModifiedToDate() {
		if(to == null || to.equals(""))
			return to;
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
		SimpleDateFormat formatBetter = new SimpleDateFormat(DATE_FORMAT_BETTER);
		GregorianCalendar c = new GregorianCalendar();
		try {
			c.setTimeInMillis(format.parse(to).getTime());
			c.add(GregorianCalendar.DAY_OF_MONTH, 1);
			c.add(GregorianCalendar.SECOND, -1);
			return formatBetter.format(c.getTime());
		} catch (ParseException e) {
			throw new RuntimeException("Could not evaluate the 'to' date" + to,e);
		}	
	}
}
