package eu.dnetlib.dlms.jdbc.ast;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;

import eu.dnetlib.dlms.jdbc.ExecutorContext;
import eu.dnetlib.dlms.jdbc.server.IExpressionExecutor;
import eu.dnetlib.miscutils.datetime.DateUtils;

/**
 * Node for Date literals.
 * 
 * @author alessia
 * 
 */
public class DateLit extends Lit {
	/** The date. */
	private Date dateTime;

	/**
	 * {@inheritDoc}
	 * 
	 * @throws SQLException
	 * 
	 * @see eu.dnetlib.dlms.jdbc.ast.Expression#evaluate(eu.dnetlib.dlms.jdbc.server.IExpressionExecutor)
	 */
	@Override
	public Object evaluate(final IExpressionExecutor executor, final ExecutorContext context) throws SQLException {
		return executor.evaluate(this, context);
	}

	/**
	 * Parses the given String in a Date. If the String cannot be parsed a RuntimeException is thrown.
	 * 
	 * @param dateString
	 *            string to parse
	 * @return a Date instance corresponding to the parsed string
	 */
	public Date parse(final String dateString) {
		Date date = null;
		try {
			date = new DateUtils().parse(dateString);
		} catch (final Exception ex) {
			final String usDatePattern = "yyyy-MM-dd";
			try {
				date = org.apache.commons.lang.time.DateUtils.parseDate(dateString, new String[] { usDatePattern });
			} catch (final ParseException e) {
				throw new RuntimeException(e);
			}
		}
		return date;
	}

	/**
	 * Constructor.
	 * 
	 * @param dateTime
	 *            the date as String
	 */
	public DateLit(final String dateTime) {
		super();
		this.dateTime = this.parse(dateTime);
	}

	public Date getDateTime() {
		return this.dateTime;
	}

	public void setDateTime(final Date dateTime) {
		this.dateTime = dateTime;
	}
}
