/*
 * 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.castor.castors;

import nuts.core.castor.AbstractCastor;
import nuts.core.castor.CastContext;
import nuts.core.castor.castors.DateTypeCastor.DateCastor;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;



public abstract class StringTypeCastor<S, T> extends AbstractCastor<S, T> {
	protected DateCastor dateCastor;
	
	public StringTypeCastor(Type fromType, Type toType, DateCastor dateCastor) {
		super(fromType, toType);
		this.dateCastor = dateCastor;
	}

	protected String convertToString(Object value) {
		if (value instanceof Date) {
			return dateCastor.getDefaultDateFormat().format((Date)value);
		}
		else if (value instanceof Calendar) {
			return dateCastor.getDefaultDateFormat().format(((Calendar)value).getTime());
		}
		return value.toString();
	}

	public static class StringCastor extends StringTypeCastor<Object, String> {
		public StringCastor(DateCastor dateCastor) {
			super(Object.class, String.class, dateCastor);
		}
		
		@Override
		protected String convertValue(Object value, CastContext context) {
			return convertToString(value);
		}
	}

	public static class StringBufferCastor extends StringTypeCastor<Object, StringBuffer> {
		public StringBufferCastor(DateCastor dateCastor) {
			super(Object.class, StringBuffer.class, dateCastor);
		}
		
		@Override
		protected StringBuffer convertValue(Object value, CastContext context) {
			return new StringBuffer(convertToString(value));
		}
	}

	public static class StringBuilderCastor extends StringTypeCastor<Object, StringBuilder> {
		public StringBuilderCastor(DateCastor dateCastor) {
			super(Object.class, StringBuilder.class, dateCastor);
		}
		
		@Override
		protected StringBuilder convertValue(Object value, CastContext context) {
			return new StringBuilder(convertToString(value));
		}
	}
}
