/*
 * Copyright 2020, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.testing.server.blackbox;

import io.spine.core.Subscribe;
import io.spine.server.event.AbstractEventSubscriber;
import io.spine.system.server.HandlerFailedUnexpectedly;

import static io.spine.json.Json.toJson;
import static java.lang.String.format;
import static java.lang.System.lineSeparator;
import static org.junit.jupiter.api.Assertions.fail;

/**
 * Performs logging of failed signals handling or fails the test depending the current
 * context exception tolerance.
 */
final class ExceptionGuard extends AbstractEventSubscriber implements ExceptionLogging {

    private ExceptionTolerance tolerance = ExceptionTolerance.RAISE;

    @Subscribe
    void on(HandlerFailedUnexpectedly event) {
        String msg = format(
                "The entity (state type `%s`) could not handle the signal `%s`:%n%s%n",
                event.getEntity().getTypeUrl(),
                event.getHandledSignal().getTypeUrl(),
                event.getError().getMessage()
        );
        switch (tolerance){
            case LOG:
                log(msg, event);
                break;
            case RAISE:
            default:
                fail(() -> msg + lineSeparator() + toJson(event));
        }
    }

    /**
     * Asks the guard to tolerate exceptions.
     */
    void tolerate() {
        tolerance = ExceptionTolerance.LOG;
    }
}

@@ -1060,85 +1060,239 @@
 ort 
-io.spine.core.Subscribe;%0Aimport io.spine.server.event.AbstractEventSubscriber
+com.google.common.annotations.VisibleForTesting;%0Aimport com.google.common.collect.ImmutableSet;%0Aimport io.spine.server.event.AbstractEventSubscriber;%0Aimport io.spine.server.type.EventClass;%0Aimport io.spine.server.type.EventEnvelope
 ;%0Aim
@@ -1819,25 +1819,820 @@
 ;%0A%0A    @
-Subscribe
+Override%0A    public ImmutableSet%3CEventClass%3E messageClasses() %7B%0A        return EventClass.setOf(HandlerFailedUnexpectedly.class);%0A    %7D%0A%0A    /**%0A     * Always dispatched %7B@link HandlerFailedUnexpectedly%7D event.%0A     */%0A    @Override%0A    public boolean canDispatch(EventEnvelope eventEnvelope) %7B%0A        return true;%0A    %7D%0A%0A    @Override%0A    protected void handle(EventEnvelope eventEnvelope) %7B%0A        HandlerFailedUnexpectedly event = (HandlerFailedUnexpectedly) eventEnvelope.message();%0A        on(event);%0A    %7D%0A%0A    /**%0A     * Throws an %7B@link org.opentest4j.AssertionFailedError AssertionFailedError%7D%0A     * unless the guard is configured to %7B@linkplain #tolerate() tolerate%7D exceptions.%0A     *%0A     * %3Cp%3EIf the guard is tolerating exceptions, logs the handler failure.%0A     */%0A    @VisibleForTesting
 %0A    voi
@@ -2974,16 +2974,17 @@
 lerance)
+ 
 %7B%0A      
@@ -3317,11 +3317,483 @@
 G;%0A    %7D
+%0A%0A    /**%0A     * %7B@inheritDoc%7D%0A     *%0A     * %3Cp%3EThe %7B@code BlackBoxBoundedContext%7D only consumes domestic events.%0A     */%0A    @Override%0A    public ImmutableSet%3CEventClass%3E domesticEventClasses() %7B%0A        return eventClasses();%0A    %7D%0A%0A    /**%0A     * %7B@inheritDoc%7D%0A     *%0A     * %3Cp%3EThe %7B@code BlackBoxBoundedContext%7D does not consume external events.%0A     */%0A    @Override%0A    public ImmutableSet%3CEventClass%3E externalEventClasses() %7B%0A        return ImmutableSet.of();%0A    %7D
 %0A%7D%0A

Refactor the guard to not die within an infinite `HandlerFailedUnexpectedly` loop while using `@Subscribe` and throwing AssertionFailedError.