/*
 Copyright 2004-2008 Paul R. Holser, Jr.  All rights reserved.
 Licensed under the Academic Free License version 3.0
 */

package joptsimple;

import java.util.List;

/**
 * <p>Specification of an option that accepts an optional argument.</p>
 *
 * @since 1.0
 * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
 * @version $Id: OptionalArgumentOptionSpec.java,v 1.5 2008/05/01 15:38:45 pholser Exp $
 */
class OptionalArgumentOptionSpec extends ArgumentAcceptingOptionSpec {
    OptionalArgumentOptionSpec( String option ) {
        super( option, false );
    }

    OptionalArgumentOptionSpec( List options, String description ) {
        super( options, false, description );
    }

    protected void detectOptionArgument( OptionParser parser, ArgumentList arguments,
        OptionSet detectedOptions ) {

        if ( arguments.hasMore() ) {
            String nextArgument = arguments.peek();

            if ( !parser.looksLikeAnOption( nextArgument ) )
                handleOptionArgument( parser, detectedOptions, arguments );
            else if ( isArgumentOfNumberType() && canConvertArgument( nextArgument ) )
                addArguments( detectedOptions, arguments.next() );
            else
                detectedOptions.addAll( options() );
        }
        else
            detectedOptions.addAll( options() );
    }

    private void handleOptionArgument( OptionParser parser, OptionSet detectedOptions,
        ArgumentList arguments ) {

        if ( parser.posixlyCorrect() ) {
            detectedOptions.addAll( options() );
            parser.noMoreOptions();
        }
        else
            addArguments( detectedOptions, arguments.next() );
    }

    void accept( OptionSpecVisitor visitor ) {
        visitor.visit( this );
    }
}
