package kr.gmtc.tss.kafka;


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

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KafkaTopicReader implements Runnable {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private final String bootstrapServers;
	private final String topic;
	
	Queue<String> rcvQueue;

    public KafkaTopicReader(String bootstrapServers, String topic, Queue<String> rcvQueue) {
        this.bootstrapServers = bootstrapServers;
        this.topic = topic;
        this.rcvQueue = rcvQueue;
    }

    public void run() {
        Properties props = new Properties();
        props.put("bootstrap.servers", bootstrapServers);
        props.put("group.id", "kafka-topic-reader-aivideo");
        props.put("auto.offset.reset", "latest");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
        	
            // 토픽 구독
            consumer.subscribe(Collections.singletonList(topic));
            
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                
                if (records.count() > 0) logger.info("topic {} 수신 건수 {}", topic, records.count());
                
                for (ConsumerRecord<String, String> record : records) {
                	rcvQueue.add(record.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
