/*
 * 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.exts.fileupload;

import nuts.core.castor.AbstractCastor;
import nuts.core.castor.CastContext;
import nuts.core.castor.CastException;
import nuts.core.lang.codec.binary.Base64;

import java.io.IOException;
import java.lang.reflect.Type;



public class UploadFileCastor<S, T extends UploadFile> extends AbstractCastor<Object, UploadFile> {
	public UploadFileCastor(Type toType) {
		super(Object.class, toType);
	}
	
	@Override
	protected UploadFile convertValue(Object value, CastContext context) {
		if (value instanceof String) {
			value = Base64.decodeBase64((String)value);
		}
		
		if (value instanceof byte[]) {
			UploadFile uf = createTarget();
			try {
				uf.setData((byte[])value);
			}
			catch (IOException e) {
				throw new CastException("Failed to convert UploadFile: " + value);
			}
			return uf;
		}

		throw new CastException("Failed to convert UploadFile: " + value.getClass());
	}
}
