package parser;

/**
 * Factory for V grammar non-terminal objects.
 */
public class VFact extends ATVFactory {
    /**
     * Token visitor to parse T1 grammar non-terminals.
     */
    private T1Fact _t1Fact;

    /**
     * Token visitor to parse T1 grammar non-terminals.
     */
    private ITokVisitor _parseT1;

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

            // initialize
            _parseT1 = _t1Fact.makeVisitor();
            return null;
        }
    };

    /**
     * Constructor for the V factory,
     *
     * @param tkz    tokenizer to use
     * @param t1Fact factory for T1 non-terminals
     */
    public VFact(ITokenizer tkz, T1Fact t1Fact) {
        super(tkz);
        _t1Fact = t1Fact;
    }

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

    /**
     * Make an V grammar non-terminal.
     *
     * @param host id token
     * @param inp  visitor-specific input
     * @return V grammar non-terminal
     */
    private V makeV(IdToken host, Object inp) {
        return new V(host, (T1) nextToken().execute(_parseT1, inp));
    }

    /**
     * Make a token visitor to parse an V non-terminal.
     *
     * @return token visitor
     */
    public ITokVisitor makeVisitor() {
        initialize();
        return new IdToken.IIdVisitor() {
            public Object idCase(IdToken host, Object param) {
                return makeV(host, param);
            }

            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 IdToken.AChainVis(successor) {
            public Object idCase(IdToken host, Object param) {
                return makeV(host, param);
            }
        };
    }
}

