package org.distributed;

import org.apache.kafka.clients.consumer.*;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class Consumer {
    public static void main(String[] args) {

        // Kafka configuration properties
        Properties props = new Properties();
        props.put(Tag.SERVER.label, Tag.SERVER_URL.label);
        props.put(Tag.DESERIALISER_KEY.label, Tag.DESERIALISER.label);
        props.put(Tag.DESERIALISER_VAL.label, Tag.DESERIALISER.label);
        props.put(Tag.GID.label, Tag.GROUP.label);

        // Creating KafkaConsumer instance
        KafkaConsumer<Object, Object> consumer = new KafkaConsumer<>(props);

        // subscribe to topic

        consumer.subscribe(Collections.singletonList(Tag.TOPIC.label));
        // Starting consuming the messages
        while (true) {

            try (consumer) { // it gave me no other way to close consumer

                // Providing poll for new records from Kafka topic
                ConsumerRecords<Object, Object> records = consumer.poll(Duration.ofMillis(100));

                // Processing the received records
                for (ConsumerRecord<Object, Object> record : records) {
                    // Printing the received message
                    System.out.println("Nerds Received a message: " + record.value());

                }

            } catch (Exception e) {
                System.err.println("Consumer: " + e.getMessage());
            }

        }

    }

}
