package eu.teraflow.automation.context;

import context.ContextOuterClass;
import context.MutinyContextServiceGrpc.MutinyContextServiceStub;
import eu.teraflow.automation.Serializer;
import eu.teraflow.automation.device.model.*;
import eu.teraflow.automation.device.model.Device;
import io.quarkus.grpc.GrpcClient;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.jboss.logging.Logger;

@ApplicationScoped
public class ContextGatewayImpl implements ContextGateway {
    private static final Logger LOGGER = Logger.getLogger(ContextGatewayImpl.class);

    @GrpcClient("context")
    MutinyContextServiceStub streamingDelegateContext;

    private final Serializer serializer;

    @Inject
    public ContextGatewayImpl(Serializer serializer) {
        this.serializer = serializer;
    }

    @Override
    public Multi<DeviceEvent> getDeviceEvents() {
        final var serializedEmpty = ContextOuterClass.Empty.newBuilder().build();

        return streamingDelegateContext
                .getDeviceEvents(serializedEmpty)
                .onItem()
                .transform(serializer::deserialize);
    }

    @Override
    public Uni<Device> getDevice(String deviceId) {
        final var serializedDeviceId = serializer.serializeDeviceId(deviceId);

        return streamingDelegateContext
                .getDevice(serializedDeviceId)
                .onItem()
                .transform(serializer::deserialize);
    }
}
