package org.jboss.as.cli.parsing;

import org.jboss.as.cli.CommandFormatException;

/**
 *
 * @author Alexey Loubyansky
 * @author Tomas Hofman (thofman@redhat.com)
 */
public class ExpressionBaseState extends DefaultParsingState {

    private final boolean exceptionIfNotResolved;

    private CharacterHandler resolvingEntranceHandler = new CharacterHandler() {
        @Override
        public void handle(ParsingContext ctx) throws CommandFormatException {
            ctx.replaceProperty(exceptionIfNotResolved);
            ExpressionBaseState.super.getEnterHandler().handle(ctx);
        }};

    public ExpressionBaseState(String id) {
        this(id, true);
        putExpressionHandler();
    }

    public ExpressionBaseState(String id, boolean exceptionIfNotResolved) {
        super(id);
        this.exceptionIfNotResolved = exceptionIfNotResolved;
        putExpressionHandler();
    }

    protected void putExpressionHandler() {
        putHandler('$', new CharacterHandler() {
            @Override
            public void handle(ParsingContext ctx) throws CommandFormatException {
                ctx.replaceProperty(true);
                final char resolvedCh = ctx.getCharacter();
                if(resolvedCh == '$') {
                    getDefaultHandler().handle(ctx);
                } else {
                    getHandler(resolvedCh).handle(ctx);
                }
            }
        });
    }

    @Override
    public CharacterHandler getEnterHandler() {
        return resolvingEntranceHandler;
    }
}
