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

/**
 * a primitive value or a Component instance as parameter
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class InstanceParameter implements Parameter {

    private String literalValue = null;
    private Object value = null;
    private Class type = null;
    private String stype = null;

    public InstanceParameter(Object obj) {
        this.value = obj;
        this.type = obj.getClass();
    }

    /**
     * may the value is the sub class of type
     *
     * @param value
     * @param type
     */
    public InstanceParameter(Object value, Class type) {
        this.value = value;
        this.type = type;
    }

    public InstanceParameter(String literalValue, String type) {
        this.literalValue = literalValue;
        this.stype = type;
    }

    public InstanceParameter(String literalValue, Class type) {
        this.literalValue = literalValue;
        this.type = type;
    }

    public Class getType() {
        return type;
    }

    public String getLiteralValue() {
        if(literalValue == null) {
            literalValue = value.toString();
        }
        return literalValue;

    }

    public Object resolveValue(Registry registry) throws ComponentException {
        if(type == null && stype != null) {
            try {
                type = registry.loadClass(stype);
            }
            catch(Exception e) {
                throw new ComponentException("load type class " + stype + " error", e);
            }
        }
        if(value == null) {
            try {
                value = type.getConstructor(new Class[]{String.class}).newInstance(new Object[]{literalValue});
            }
            catch(Exception e) {
                throw new ComponentException("resolve component parameter value error", e);
            }
        }
        return value;
    }

    public String toString() {
        return "ComponentInstanceParameter{" +
                "type=" + type +
                ", value=" + (value == null ? "NOT RESOVLED" : value.toString()) +
                "}";
    }

    public static void main(String[] args) {

    }

}

