/*
 * Copyright 2019, 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.server.commandbus;

import io.spine.core.Ack;
import io.spine.core.Command;
import io.spine.core.TenantId;
import io.spine.server.bus.BusFilter;
import io.spine.server.type.CommandEnvelope;
import io.spine.system.server.event.CommandReceived;
import io.spine.system.server.SystemWriteSide;
import io.spine.system.server.WriteSideFunction;

import java.util.Optional;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A {@link CommandBus} filter which watches the commands as they appear in the bus.
 *
 * <p>The filter notifies the {@link io.spine.system.server.SystemContext SystemContext} about
 * new commands with a {@link CommandReceived} system event.
 *
 * <p>The filter never terminates the command processing, i.e. {@link #accept(CommandEnvelope)}
 * always returns an empty value.
 */
final class CommandReceivedTap implements BusFilter<CommandEnvelope> {

    private final WriteSideFunction writeSideFunction;

    CommandReceivedTap(WriteSideFunction function) {
        this.writeSideFunction = checkNotNull(function);
    }

    @Override
    public Optional<Ack> accept(CommandEnvelope envelope) {
        CommandReceived systemEvent = systemEvent(envelope.command());
        TenantId tenantId = envelope.tenantId();
        SystemWriteSide writeSide = writeSideFunction.get(tenantId);
        writeSide.postEvent(systemEvent);
        return Optional.empty();
    }

    private static CommandReceived systemEvent(Command domainCommand) {
        CommandReceived result = CommandReceived
                .newBuilder()
                .setId(domainCommand.getId())
                .setPayload(domainCommand)
                .build();
        return result;
    }
}

@@ -1361,16 +1361,77 @@
 unction;
+%0Aimport io.spine.system.server.event.CommandReceivedVBuilder;
 %0A%0Aimport
@@ -2613,16 +2613,24 @@
 Received
+VBuilder
 %0A       

Use vBuilder