/*
 * Copyright (C) 2015 Francis Galiegue <fgaliegue@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.fge.grappa.run;

import com.github.fge.grappa.buffers.InputBuffer;
import com.github.fge.grappa.internal.NonFinalForTesting;
import com.github.fge.grappa.matchers.base.Matcher;
import com.github.fge.grappa.rules.Rule;
import com.github.fge.grappa.run.events.MatchContextEvent;
import com.github.fge.grappa.run.events.MatchFailureEvent;
import com.github.fge.grappa.run.events.MatchSuccessEvent;
import com.github.fge.grappa.run.events.PostParseEvent;
import com.github.fge.grappa.run.events.PreMatchEvent;
import com.github.fge.grappa.run.events.PreParseEvent;
import com.google.common.eventbus.EventBus;
import com.github.fge.grappa.run.context.MatcherContext;

import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Objects;

/**
 * The most basic of all {@link ParseRunner} implementations. It runs a rule
 * against a given input text and builds a corresponding {@link ParsingResult}
 * instance. However, it does not report any parse errors nor recover from them.
 * Instead it simply marks the ParsingResult as "unmatched" if the input is not
 * valid with regard to the rule grammar.It never causes the parser to perform
 * more than one parsing run and is the fastest way to determine whether a given
 * input conforms to the rule grammar.
 */
@SuppressWarnings("DesignForExtension")
@ParametersAreNonnullByDefault
@NonFinalForTesting
public class ListeningParseRunner<V>
    extends AbstractParseRunner<V>
    implements MatchHandler
{
    private final EventBus bus = new EventBus();
    /**
     * Creates a new BasicParseRunner instance for the given rule.
     *
     * @param rule the parser rule
     */
    public ListeningParseRunner(final Rule rule)
    {
        super(rule);
    }

    // TODO: replace with a supplier mechanism
    public final void registerListener(final ParseRunnerListener<V> listener)
    {
        bus.register(listener);
    }

    @Override
    public ParsingResult<V> run(final InputBuffer inputBuffer)
    {
        Objects.requireNonNull(inputBuffer, "inputBuffer");
        resetValueStack();

        final MatcherContext<V> rootContext
            = createRootContext(inputBuffer, this);
        bus.post(new PreParseEvent<>(rootContext));
        final boolean matched = rootContext.runMatcher();
        final ParsingResult<V> result
            = createParsingResult(matched, rootContext);
        bus.post(new PostParseEvent<>(result));
        return result;
    }

    @Override
    public <T> boolean match(final MatcherContext<T> context)
    {
        final Matcher matcher = context.getMatcher();

        final PreMatchEvent<T> preMatchEvent = new PreMatchEvent<>(context);
        bus.post(preMatchEvent);

        // FIXME: is there any case at all where context.getMatcher() is null?
        @SuppressWarnings("ConstantConditions")
        final boolean match = matcher.match(context);

        final MatchContextEvent<T> postMatchEvent = match
            ? new MatchSuccessEvent<>(context)
            : new MatchFailureEvent<>(context);
        bus.post(postMatchEvent);

        return match;
    }
}

@@ -698,24 +698,81 @@
 nputBuffer;%0A
+import com.github.fge.grappa.exceptions.GrappaException;%0A
 import com.g
@@ -817,16 +817,16 @@
 esting;%0A
-
 import c
@@ -910,16 +910,73 @@
 s.Rule;%0A
+import com.github.fge.grappa.run.context.MatcherContext;%0A
 import c
@@ -1370,51 +1370,118 @@
 om.g
-ithub.fge.grappa.run.context.MatcherContext
+oogle.common.eventbus.SubscriberExceptionContext;%0Aimport com.google.common.eventbus.SubscriberExceptionHandler
 ;%0A%0Ai
@@ -2286,52 +2286,491 @@
     
-private final EventBus bus = new EventBus();
+// TODO: does it need to be volatile?%0A    private volatile Throwable throwable = null;%0A%0A    private final EventBus bus = new EventBus(new SubscriberExceptionHandler()%0A    %7B%0A        @Override%0A        public void handleException(final Throwable exception,%0A            final SubscriberExceptionContext context)%0A        %7B%0A            if (throwable == null)%0A                throwable = exception;%0A            else%0A                throwable.addSuppressed(exception);%0A        %7D%0A    %7D);%0A    
 %0A   
@@ -3459,24 +3459,164 @@
 tContext));%0A
+%0A        if (throwable != null)%0A            throw new GrappaException(%22parsing listener error (before parse)%22,%0A                throwable);%0A%0A
         fina
@@ -3748,32 +3748,33 @@
 , rootContext);%0A
+%0A
         bus.post
@@ -3805,16 +3805,155 @@
 sult));%0A
+%0A        if (throwable != null)%0A            throw new GrappaException(%22parsing listener error (after parse)%22,%0A                throwable);%0A%0A
         
@@ -4214,32 +4214,171 @@
 reMatchEvent);%0A%0A
+        if (throwable != null)%0A            throw new GrappaException(%22parsing listener error (before match)%22,%0A                throwable);%0A%0A
         // FIXME
@@ -4688,32 +4688,33 @@
 ent%3C%3E(context);%0A
+%0A
         bus.post
@@ -4724,32 +4724,170 @@
 stMatchEvent);%0A%0A
+        if (throwable != null)%0A            throw new GrappaException(%22parsing listener error (after match)%22,%0A                throwable);%0A%0A
         return m

handle exception from listeners...