package uk.ac.starlink.task;

import uk.ac.starlink.util.LoadException;
import uk.ac.starlink.util.ObjectFactory;

/**
 * Parameter whose (user-supplied) string values correspond to nicknames
 * from an {@link ObjectFactory}.  The {@link #objectValue} method returns
 * the corresponding object generated by the factory for that nickname.
 *
 * @author   Mark Taylor
 * @since    22 Nov 2006
 */
public class ObjectFactoryParameter extends Parameter {

    private final ObjectFactory factory_;
    private Object objValue_;

    /**
     * Constructor.
     *
     * @param  name  parameter name
     * @param  factory   object factory
     */
    public ObjectFactoryParameter( String name, ObjectFactory factory ) {
        super( name );
        factory_ = factory;
    }

    public String getUsage() {
        StringBuffer sbuf = new StringBuffer();
        String[] nickNames = factory_.getNickNames();
        for ( int i = 0; i < nickNames.length; i++ ) {
            if ( i > 0 ) {
                sbuf.append( '|' );
            }
            sbuf.append( nickNames[ i ] );
        }
        return sbuf.toString();
    }

    public void setValueFromString( Environment env, String stringval )
            throws TaskException {
        try {
            objValue_ = factory_.createObject( stringval );
        }
        catch ( LoadException e ) {
            throw new ParameterValueException( this, e );
        }
        super.setValueFromString( env, stringval );
    }

    /**
     * Returns the object created by this object's factory using its
     * string value as a nickname.
     * 
     * @param   env   execution environment
     */
    public Object objectValue( Environment env ) throws TaskException {
        checkGotValue( env );
        return objValue_;
    }
}
