package com.sqx.nsqChannel.config;

import com.github.brainlag.nsq.NSQConsumer;
import com.github.brainlag.nsq.lookup.DefaultNSQLookup;
import com.github.brainlag.nsq.lookup.NSQLookup;

public class NSQConsumers {

    private final String nsqLookupAddress;
    private final int nsqLookupPort;
    private final String topics;
    private final String channelName;
    private final NSQMessageHandlerAdapter handlerAdapter;
    private NSQConsumer consumer;

    public NSQConsumers(String nsqLookupAddress, int nsqLookupPort,String topics, String channelName, NSQMessageHandlerAdapter handlerAdapter) {
        this.nsqLookupAddress = nsqLookupAddress;
        this.nsqLookupPort = nsqLookupPort;
        this.topics = topics;
        this.channelName = channelName;
        this.handlerAdapter = handlerAdapter;
        start();
    }

    public void start() {
        try {
            NSQLookup lookup = new DefaultNSQLookup();
            lookup.addLookupAddress(nsqLookupAddress, nsqLookupPort);

            consumer = new NSQConsumer(lookup, topics, channelName, (message) -> {
                handlerAdapter.handleMessage(message.getMessage());
                message.finished();
            });
            consumer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        if (consumer != null) {
            consumer.shutdown();
        }
    }
}
