package com.huawei.hwclouds.drs.avro;

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

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import static java.lang.System.exit;

public class Consumer {

    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("java -jar drs-avro-read-1.0.jar host topic");
            return;
        }
        String host = args[0];
        String topic = args[1];

        String groupId = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println("host=" + host + ",topic=" + topic);

        Properties props = new Properties();
        props.put("bootstrap.servers", host);
        props.put("group.id", groupId);
        //props.put("isolation.level","read_committed");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
        props.put("auto.offset.reset", "earliest");

        KafkaConsumer<String, byte[]> consumer = new KafkaConsumer<String, byte[]>(props);

        consumer.subscribe(Collections.singletonList(topic));

        AvroObject avroObject = new AvroObject();
        while (true) {
            ConsumerRecords<String, byte[]> records = consumer.poll(100);
            for (ConsumerRecord<String, byte[]> record : records) {
                System.out.println(record);
                if (record != null && record.value() != null) {
                    //从kafka获取的数据进行反序列生成Record类
                    Record rec = avroObject.getData(record.value());
                    if (rec != null) {
                        //解析Record对象信息
                        avroObject.showRecord(rec);
                    }
                }
            }
        }
    }


}
