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.AlarmFeedMessage;
import mxaccess_gateway.v1.MxaccessGateway.StreamAlarmsRequest;

/**
 * Cancellable handle returned by {@code streamAlarms}.
 *
 * <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 MxGatewayAlarmFeedSubscription implements AutoCloseable {
    private final AtomicReference<ClientCallStreamObserver<StreamAlarmsRequest>> requestStream = new AtomicReference<>();
    private final AtomicBoolean cancelled = new AtomicBoolean();

    ClientResponseObserver<StreamAlarmsRequest, AlarmFeedMessage> wrap(StreamObserver<AlarmFeedMessage> observer) {
        return new ClientResponseObserver<>() {
            @Override
            public void beforeStart(ClientCallStreamObserver<StreamAlarmsRequest> stream) {
                requestStream.set(stream);
                if (cancelled.get()) {
                    stream.cancel("client cancelled alarm feed", null);
                }
            }

            @Override
            public void onNext(AlarmFeedMessage 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<StreamAlarmsRequest> stream = requestStream.get();
        if (stream != null) {
            stream.cancel("client cancelled alarm feed", null);
        }
    }

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