/**
 * 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.pulsar.io.kafka;

import lombok.Getter;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.pulsar.io.core.PushSource;
import org.apache.pulsar.io.core.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Simple Kafka Source to transfer messages from a Kafka topic
 */
public class KafkaSource<V> extends PushSource<V> {

    private static final Logger LOG = LoggerFactory.getLogger(KafkaSource.class);

    private Consumer<String, V> consumer;
    private Properties props;
    private KafkaSourceConfig kafkaSourceConfig;
    Thread runnerThread;

    private java.util.function.Consumer<Record<V>> consumeFunction;

    @Override
    public void open(Map<String, Object> config) throws Exception {
        kafkaSourceConfig = KafkaSourceConfig.load(config);
        if (kafkaSourceConfig.getTopic() == null
                || kafkaSourceConfig.getBootstrapServers() == null
                || kafkaSourceConfig.getGroupId() == null
                || kafkaSourceConfig.getFetchMinBytes() == 0
                || kafkaSourceConfig.getAutoCommitIntervalMs() == 0
                || kafkaSourceConfig.getSessionTimeoutMs() == 0) {
            throw new IllegalArgumentException("Required property not set.");
        }

        props = new Properties();

        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaSourceConfig.getBootstrapServers());
        props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaSourceConfig.getGroupId());
        props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, kafkaSourceConfig.getFetchMinBytes().toString());
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, kafkaSourceConfig.getAutoCommitIntervalMs().toString());
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, kafkaSourceConfig.getSessionTimeoutMs().toString());

        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, kafkaSourceConfig.getKeyDeserializationClass());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, kafkaSourceConfig.getValueDeserializationClass());

        this.start();

    }

    @Override
    public void setConsumer(java.util.function.Consumer<Record<V>> consumerFunction) {
        this.consumeFunction = consumerFunction;
    }

    @Override
    public void close() throws InterruptedException {
        LOG.info("Stopping kafka source");
        if (runnerThread != null) {
            runnerThread.interrupt();
            runnerThread.join();
            runnerThread = null;
        }
        if(consumer != null) {
            consumer.close();
            consumer = null;
        }
        LOG.info("Kafka source stopped.");
    }

    public void start() {
        runnerThread = new Thread(() -> {
            LOG.info("Starting kafka source");
            consumer = new KafkaConsumer<>(props);
            consumer.subscribe(Arrays.asList(kafkaSourceConfig.getTopic()));
            LOG.info("Kafka source started.");
            ConsumerRecords<String, V> consumerRecords;
            while(true){
                consumerRecords = consumer.poll(1000);
                CompletableFuture<?>[] futures = new CompletableFuture<?>[consumerRecords.count()];
                int index = 0;
                for (ConsumerRecord<String, V> consumerRecord : consumerRecords) {
                    LOG.debug("Record received from kafka, key: {}. value: {}", consumerRecord.key(), consumerRecord.value());
                    KafkaRecord<V> record = new KafkaRecord<>(consumerRecord);
                    consumeFunction.accept(record);
                    futures[index] = record.getCompletableFuture();
                    index++;
                }
                if (!kafkaSourceConfig.isAutoCommitEnabled()) {
                    try {
                        CompletableFuture.allOf(futures).get();
                        consumer.commitSync();
                    } catch (ExecutionException | InterruptedException ex) {
                        break;
                    }
                }
            }

        });
        runnerThread.setName("Kafka Source Thread");
        runnerThread.start();
    }

    static private class KafkaRecord<V> implements Record<V> {
        private final ConsumerRecord<String, V> record;
        @Getter
        private final CompletableFuture<Void> completableFuture = new CompletableFuture();

        public KafkaRecord(ConsumerRecord<String, V> record) {
            this.record = record;
        }
        @Override
        public String getPartitionId() {
            return Integer.toString(record.partition());
        }

        @Override
        public long getRecordSequence() {
            return record.offset();
        }

        @Override
        public V getValue() {
            return record.value();
        }

        @Override
        public void ack() {
            completableFuture.complete(null);
        }
    }
}

@@ -1535,16 +1535,25 @@
 %0Apublic 
+abstract 
 class Ka
@@ -1694,25 +1694,30 @@
 onsumer%3C
-String, V
+byte%5B%5D, byte%5B%5D
 %3E consum
@@ -4204,25 +4204,30 @@
 Records%3C
-String, V
+byte%5B%5D, byte%5B%5D
 %3E consum
@@ -4484,25 +4484,30 @@
 rRecord%3C
-String, V
+byte%5B%5D, byte%5B%5D
 %3E consum
@@ -4735,24 +4735,54 @@
 nsumerRecord
+, extractValue(consumerRecord)
 );%0A         
@@ -5401,24 +5401,100 @@
 t();%0A    %7D%0A%0A
+    public abstract V extractValue(ConsumerRecord%3Cbyte%5B%5D, byte%5B%5D%3E record);%0A%0A
     static p
@@ -5581,33 +5581,69 @@
 rRecord%3C
-String, V%3E record
+byte%5B%5D, byte%5B%5D%3E record;%0A        private final V value
 ;%0A      
@@ -5790,25 +5790,66 @@
 ord%3C
-String, V%3E record
+byte%5B%5D, byte%5B%5D%3E record,%0A                           V value
 ) %7B%0A
@@ -5874,32 +5874,64 @@
 ecord = record;%0A
+            this.value = value;%0A
         %7D%0A      
@@ -6229,22 +6229,13 @@
 urn 
-record.
 value
-()
 ;%0A  

Make the KakfaSource abstract by allowing users to implement method to extract value (#1842)