package com.zb.mom.ww.mxgateway.client;

import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import mxaccess_gateway.v1.MxaccessGateway.ActiveAlarmSnapshot;
import mxaccess_gateway.v1.MxaccessGateway.QueryActiveAlarmsRequest;

/**
 * Cancellable handle returned by {@code queryActiveAlarms}.
 *
 * <p>Wraps a caller-supplied {@link StreamObserver} and exposes a
 * {@link #cancel()} entry point that aborts the underlying gRPC call. The
 * subscription also implements {@link AutoCloseable} so it can participate in
 * try-with-resources blocks.
 */
public final class MxGatewayActiveAlarmsSubscription implements AutoCloseable {
    private final AtomicReference<ClientCallStreamObserver<QueryActiveAlarmsRequest>> requestStream = new AtomicReference<>();
    private final AtomicBoolean cancelled = new AtomicBoolean();

    ClientResponseObserver<QueryActiveAlarmsRequest, ActiveAlarmSnapshot> wrap(StreamObserver<ActiveAlarmSnapshot> observer) {
        return new ClientResponseObserver<>() {
            @Override
            public void beforeStart(ClientCallStreamObserver<QueryActiveAlarmsRequest> stream) {
                requestStream.set(stream);
                if (cancelled.get()) {
                    stream.cancel("client cancelled active-alarms query", null);
                }
            }

            @Override
            public void onNext(ActiveAlarmSnapshot value) {
                observer.onNext(value);
            }

            @Override
            public void onError(Throwable error) {
                observer.onError(error);
            }

            @Override
            public void onCompleted() {
                observer.onCompleted();
            }
        };
    }

    /**
     * Cancels the underlying gRPC call. Safe to invoke before the call has
     * started; cancellation is recorded and applied as soon as the stream
     * attaches.
     */
    public void cancel() {
        cancelled.set(true);
        ClientCallStreamObserver<QueryActiveAlarmsRequest> stream = requestStream.get();
        if (stream != null) {
            stream.cancel("client cancelled active-alarms query", null);
        }
    }

    @Override
    public void close() {
        cancel();
    }
}
