/*
 * 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.oxm.adapter;

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

/**
 * DateAdapter adapts a Java Date value to a DOM Element with the specified
 * property name containing the Date's value. e.g. a property
 * 
 * <pre>
 * Date getFoo() {
 * 	return new Date(1234);
 * }
 * </pre>
 * 
 * will appear in the result DOM as: <foo>1234</foo>
 * 
 */
public class DateElementAdapter extends StringElementAdapter {

	private SimpleDateFormat dateFormat;

	public DateElementAdapter() {
	}

	public DateElementAdapter(AdapterFactory adapterFactory, NodeAdapter parent,
			String propertyName, String value) {
		setContext(adapterFactory, parent, propertyName, value);
	}

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

	protected Date getDateValue() {
		Object value = getPropertyValue();
		if (value instanceof Date) {
			return (Date)value;
		}
		else if (value instanceof Calendar) {
			return ((Calendar)value).getTime();
		}
		else {
			throw new IllegalArgumentException("The value(" + value.getClass() + ") must be Data/Calendar type.");
		}
	}
	
	/**
	 * Get the object to be adapted as a String value.
	 */
	@Override
	protected String getStringValue() {
		if (dateFormat != null) {
			return dateFormat.format(getDateValue());
		}
		else {
			return String.valueOf(getDateValue().getTime());
		}
	}
}
