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

/**
 * ref the Component by Class type
 * it return the first Component object appriciate the type
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class ImplemetationRefParameter implements RefParameter {
    private Class type;
    private ComponentName refComponentName;
    private Component value = null;

    public ImplemetationRefParameter(Class type) {
        this.type = type;
    }

    public Class getType() {
        return type;
    }

    /**
     * the ref ComponentName
     *
     * @return
     */
    public String getLiteralValue() {
        return refComponentName == null ? null : refComponentName.toString();
    }

    public ComponentName getRefComponentName() {
        return refComponentName;
    }

    public Object resolveValue(Registry registry) throws ComponentException {
        if(value != null) return value;
        ComponentMeta meta = registry.getFirstComponentMetabyImplemetation(type);
        if(meta == null) { // not found component in registry, try to register it
            throw new ComponentException("not found component by implemention type " + type.getName());
/*
      if(checkConcrete(type)){
        meta = registry.registerComponent(type);
      }
      else {
        throw new ComponentException("not found Component by type " + type.getName());
      }
*/

        }
        refComponentName = meta.getComponentName();
        value = meta.getComponentInstance();
        return value;
    }

    private static boolean checkConcrete(Class implementation) {
        // Assert that the component class is concrete.
        boolean isAbstract = (implementation.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT;
        boolean isPrivate = (implementation.getModifiers() & Modifier.PRIVATE) == Modifier.PRIVATE;
        boolean isProtected = (implementation.getModifiers() & Modifier.PROTECTED) == Modifier.PROTECTED;
        if(implementation.isInterface() || isAbstract || isPrivate || isProtected) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {

    }
}

