/*
 * Copyright 2020 Wuyi Chen.
 *
 * Licensed 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 com.kafkadefinitiveguide.consumer.deserializer.avrodeserializer;

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

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

/**
 * Receive Customer (message) by Avro deserializer.
 * 
 * <p>Customer is not Pojo object, it is Avro object generated by avro-tools.jar.
 *
 * @author  Wuyi Chen
 * @date    06/06/2020
 * @version 1.0
 * @since   1.0
 */
public class CustomerConsumer {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("bootstrap.servers",    "localhost:9092");
		props.put("group.id",             "CountryCounter");
		props.put("key.deserializer",     "org.apache.kafka.common.serialization.StringDeserializer");
		props.put("value.deserializer",   "io.confluent.kafka.serializers.KafkaAvroDeserializer");
		props.put("specific.avro.reader", "true");
		props.put("schema.registry.url",  "localhost:8081");
		
		String topic = "customerContacts";
				
		KafkaConsumer<String, Customer> consumer = new KafkaConsumer<>(props);
		consumer.subscribe(Collections.singletonList(topic));

		System.out.println("Reading topic:" + topic);

		while (true) {
			ConsumerRecords<String, Customer> records = consumer.poll(Duration.ofMillis(1000));

			for (ConsumerRecord<String, Customer> record: records) {
				System.out.println("Current customer name is: " + record.value().getName());
			}
			consumer.commitSync();
		}
	}
}
