/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.connector.pulsar.source.enumerator.cursor.stop;

import org.apache.flink.connector.pulsar.source.enumerator.cursor.StopCursor;
import org.apache.flink.connector.pulsar.source.enumerator.topic.TopicPartition;

import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.schema.GenericRecord;
import org.apache.pulsar.client.impl.schema.AutoConsumeSchema;

import java.util.Objects;

/**
 * A stop cursor that initialize the position to the latest message id. The offsets initialization
 * are taken care of by the {@code PulsarPartitionSplitReaderBase} instead of by the {@code
 * PulsarSourceEnumerator}. We would include the latest message available in Pulsar by default.
 */
public class LatestMessageStopCursor implements StopCursor {
    private static final long serialVersionUID = 1702059838323965723L;

    private static final String SUBSCRIPTION_NAME = LatestMessageStopCursor.class.getSimpleName();

    private MessageId messageId;
    private final boolean inclusive;

    public LatestMessageStopCursor(boolean inclusive) {
        this.inclusive = inclusive;
    }

    @Override
    public StopCondition shouldStop(Message<?> message) {
        MessageId current = message.getMessageId();
        return StopCondition.compare(messageId, current, inclusive);
    }

    @Override
    public void open(PulsarClient client, TopicPartition partition) throws PulsarClientException {
        if (messageId == null) {
            Consumer<GenericRecord> consumer = null;
            try {
                consumer =
                        client.newConsumer(new AutoConsumeSchema())
                                .topic(partition.getFullTopicName())
                                .subscriptionName(SUBSCRIPTION_NAME)
                                .subscribe();
                this.messageId = consumer.getLastMessageId();
            } finally {
                if (consumer != null) {
                    consumer.unsubscribe();
                    consumer.close();
                }
            }
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        LatestMessageStopCursor that = (LatestMessageStopCursor) o;
        return inclusive == that.inclusive && Objects.equals(messageId, that.messageId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(messageId, inclusive);
    }
}
