package jp.sourceforge.glad.org.seasar.framework.model.impl;

import java.util.Collection;

import jp.sourceforge.glad.org.seasar.framework.model.ModelHelper;

import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.deployer.InstanceDefFactory;
import org.seasar.framework.container.impl.ComponentDefImpl;
import org.seasar.framework.container.impl.S2ContainerImpl;

/**
 * @author GLAD!!
 */
public class ModelHelperImpl implements ModelHelper {

    S2Container container;

    public void setContainer(final S2Container container) {
        this.container = container;
    }

    public void injectDependency(final Object model) {
        // 実装は暫定。
        if (model == null) {
            return;
        }
        final Class<?> clazz = model.getClass();
        if (clazz.isArray()) {
            assert !clazz.getComponentType().isPrimitive();
            injectDependency((Object[]) model);
            return;
        }
        if (model instanceof Collection) {
            injectDependency((Collection<?>) model);
            return;
        }
        final S2Container c = getContainer(clazz);
        c.injectDependency(model);
    }

    void injectDependency(final Object[] models) {
        if (models.length == 0) {
            return;
        }
        final Class<?> clazz = models.getClass().getComponentType();
        final S2Container c = getContainer(clazz);
        for (final Object component : models) {
            c.injectDependency(component);
        }
    }

    void injectDependency(final Collection<?> models) {
        if (models.isEmpty()) {
            return;
        }
        final Class<?> clazz = models.iterator().next().getClass();
        final S2Container c = getContainer(clazz);
        for (final Object component : models) {
            c.injectDependency(component);
        }
    }

    S2Container getContainer(final Class<?> clazz) {
        if (container.hasComponentDef(clazz)) {
            return container;
        }
        final S2Container c = new S2ContainerImpl();
        c.include(container);
        final ComponentDefImpl cd = new ComponentDefImpl(clazz);
        cd.setInstanceDef(InstanceDefFactory.OUTER);
        c.register(cd);
        return c;
    }

}
