package jp.sourceforge.glad.converter;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtilsBean;

public class BeanConverter {

    private final BeanUtilsBean beanUtils;

    public BeanConverter() {
        beanUtils = new BeanUtilsBean();
    }

    public BeanUtilsBean getBeanUtils() {
        return beanUtils;
    }

    public <T> T convert(Class<T> clazz, Object source) {
        T target = newInstance(clazz);
        copy(source, target);
        return target;
    }

    public void copy(Object source, Object target) {
        doCopy(source, target);
    }

    <T> T newInstance(Class<T> clazz) {
        try {
            Constructor<T> c = clazz.getConstructor();
            return c.newInstance();
        } catch (NoSuchMethodException e) {
            throw new ConverterException(e);
        } catch (InstantiationException e) {
            throw new ConverterException(e);
        } catch (IllegalAccessException e) {
            throw new ConverterException(e);
        } catch (InvocationTargetException e) {
            throw new ConverterException(e.getCause());
        }
    }

    void doCopy(Object source, Object target) {
        try {
            beanUtils.copyProperties(target, source);
        } catch (IllegalAccessException e) {
            throw new ConverterException(e);
        } catch (InvocationTargetException e) {
            throw new ConverterException(e.getCause());
        }
    }

}
