/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.editors.layout.requests;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaClass;
import org.eclipse.gef.requests.CreationFactory;

public class BeanCreationFactory implements CreationFactory {

	private Object type;

	private Map properties;

	public BeanCreationFactory(Object type, Map properties) {
		super();
		this.type = type;
		this.properties = properties;
	}

	public BeanCreationFactory(Object type) {
		this(type, null);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.requests.CreationFactory#getNewObject()
	 */
	public Object getNewObject() {
		Object bean = null;
		try {
			/* Create bean instance */
			if (type instanceof Class) {
				bean = ((Class) type).newInstance();
			} else if (type instanceof DynaClass) {
				bean = ((DynaClass) type).newInstance();
			}

			/* Populate initial values to bean */
			if (bean != null && properties != null) {
				BeanUtils.populate(bean, properties);
			}
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bean;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.requests.CreationFactory#getObjectType()
	 */
	public Object getObjectType() {
		return type;
	}

}
