package parser;

/**
 * Factory for E1a grammar non-terminal objects.
 */
public class E1aFact extends ATVFactory {
    /**
     * Factory for E grammar non-terminals.
     */
    private EFact _eFact;

    /**
     * Visitor for E grammar non-terminals.
     */
    private ITokVisitor _parseE;

    /**
     * Initializer lambda for this factory.
     */
    private ILambda _initializer = new ILambda() {
        public Object apply(Object param) {
            // change state to no-op
            _initializer = NoOpLambda.Singleton;

            // initialize
            _parseE = _eFact.makeVisitor();
            return null;
        }
    };

    /**
     * Constructor for the E1a factory.
     *
     * @param tkz   tokenizer to use
     * @param eFact factory for E grammar non-terminals
     */
    public E1aFact(ITokenizer tkz, EFact eFact) {
        super(tkz);
        _eFact = eFact;
    }

    /**
     * Constructor for the E1a factory, Does not take a factory for E grammar non-terminals. That factory has to be set
     * using setParseEFactory().
     *
     * @param tkz tokenizer to use
     */
    public E1aFact(ITokenizer tkz) {
        super(tkz);
    }

    /**
     * Set the factory for E grammar non-terminals.
     *
     * @param eFact factory for E grammar non-terminals
     */
    public void setParseEFactory(EFact eFact) {
        _eFact = eFact;
    }

    /**
     * Make a token visitor to parse an E1a non-terminal.
     *
     * @return token visitor
     */
    public ITokVisitor makeVisitor() {
        initialize();
        return new PlusToken.IPlusVisitor() {
            public Object plusCase(PlusToken host, Object inp) {
                return new E1a(host, (E) nextToken().execute(_parseE, inp));
            }

            public Object defaultCase(AToken host, Object param) {
                throw new IllegalArgumentException("Wrong token: '" + host + "'");
            }
        };
    }

    /**
     * Make a token visitor that delegates to the given visitor in a chain of responsibility
     *
     * @param successor visitor to serve as successor in the chain
     */
    public ITokVisitor makeChainedVisitor(final ITokVisitor successor) {
        initialize();
        return new PlusToken.AChainVis(successor) {
            public Object plusCase(PlusToken host, Object inp) {
                return new E1a(host, (E) nextToken().execute(_parseE, inp));
            }
        };
    }

    /**
     * Make the visitor.
     */
    private void initialize() {
        _initializer.apply(null);

    }
}

