/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */
package org.jfox.framework;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.jfox.framework.util.Classes;

/**
 * method injector
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class PropertyComponentFactory extends DecorateComponentFactory {
    private ParameterPack[] paramPacks;

    public PropertyComponentFactory(InstantiatingComponentFactory delegate, ParameterPack[] propParamPacks) {
        super(delegate);
        this.paramPacks = propParamPacks;
    }

    public Component makeComponent() throws ComponentException {
        Component component = super.makeComponent();
        doMethods(component);
        return component;
    }

    public ParameterPack[] getParameterPacks() {
        return paramPacks;
    }

    protected void doMethods(Component component) throws ComponentException {
        if(paramPacks == null || paramPacks.length == 0) return;
        for(int i = 0; i < paramPacks.length; i++) {
            ParameterPack pack = paramPacks[i];
            doMethod(component, pack);
        }
    }

    private void doMethod(Component component, ParameterPack pack) throws ComponentException {
        Object[] params = parseParameters(new Parameter[]{pack.getParameter()});
        Class[] types = parseParamTypes(new Parameter[]{pack.getParameter()});


        Method method = null;
        try {
            method = Classes.getMethod(component.getClass(), pack.getName(), types);
        }
        catch(Exception e) {
            throw new ComponentException("getMethod " + Arrays.asList(types) + " error", e);
        }
        try {
            method.invoke(component, params);
        }
        catch(Exception e) {
            throw new ComponentException("do method " + pack.getName() + " error", e);
        }
    }

    public static void main(String[] args) {

    }
}

