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

package joptsimple;

import java.util.Iterator;
import java.util.List;

/**
 * <p>Can tell whether or not options are well-formed.</p>
 *
 * @since 1.0
 * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
 * @version $Id: ParserRules.java,v 1.3 2008/04/08 03:20:18 pholser Exp $
 */
class ParserRules {
    static final char HYPHEN_CHAR = '-';
    static final String HYPHEN = String.valueOf( HYPHEN_CHAR );
    static final String DOUBLE_HYPHEN = "--";
    static final String OPTION_TERMINATOR = DOUBLE_HYPHEN;
    static final String RESERVED_FOR_EXTENSIONS = "W";

    protected ParserRules() {
        throw new UnsupportedOperationException();
    }

    static boolean isShortOptionToken( String argument ) {
        return argument.startsWith( HYPHEN )
            && !HYPHEN.equals( argument )
            && !isLongOptionToken( argument );
    }

    static boolean isLongOptionToken( String argument ) {
        return argument.startsWith( DOUBLE_HYPHEN ) && !isOptionTerminator( argument );
    }

    static boolean isOptionTerminator( String argument ) {
        return OPTION_TERMINATOR.equals( argument );
    }

    static void checkLegalOption( String option ) {
        if ( option.startsWith( HYPHEN ) )
            throw new IllegalOptionSpecificationException( String.valueOf( option ) );

        for ( int i = 0; i < option.length(); ++i )
            checkLegalOptionCharacter( option.charAt( i ) );
    }

    static void checkLegalOptions( List options ) {
        for ( Iterator iter = options.iterator(); iter.hasNext(); )
            checkLegalOption( (String) iter.next() );
    }

    private static void checkLegalOptionCharacter( char option ) {
        if ( !( Character.isLetterOrDigit( option ) || isAllowedPunctuation( option ) ) )
            throw new IllegalOptionSpecificationException( String.valueOf( option ) );
    }

    private static boolean isAllowedPunctuation( char option ) {
        String allowedPunctuation = "?." + HYPHEN_CHAR;
        return allowedPunctuation.indexOf( option ) != -1;
    }
}
