/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.bind.adaptors;

import nuts.core.bind.SourceAdaptor;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Use SimpleDateFormat to convert Date Type Value 
 */
public class DateAdaptor implements SourceAdaptor {
	private SimpleDateFormat dateFormat;
	private boolean toTime = true;

	/**
	 * Constructor
	 */
	public DateAdaptor() {
	}

	/**
	 * @param dateFormat the dateFormat to set
	 */
	public void setDateFormat(String dateFormat) {
		this.dateFormat = new SimpleDateFormat(dateFormat);
	}

	/**
	 * @param toTime the toTime to set
	 */
	public void setToTime(boolean toTime) {
		this.toTime = toTime;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object apply(Object value) {
		if (value == null) {
			return null;
		}

		Date d;
		if (value instanceof Calendar) {
			d = ((Calendar)value).getTime(); 
		}
		else if (value instanceof Date) {
			d = (Date)value;
		}
		else {
			throw new IllegalArgumentException("The value[" + value.getClass() + "] must be Date/Calendar type.");
		}
		
		return processDateValue(d);
	}

	protected Object processDateValue(Date value) {
		if (dateFormat != null){
			return dateFormat.format(value);
		}
		else if (toTime) {
			return value.getTime();
		}
		else {
			return value;
		}
	}
}

