package com.mortals.xhx.queue;

import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.extern.apachecommons.CommonsLog;
import org.slf4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务端消费消息服务
 *
 * @author: zxfei
 * @date: 2021/11/22 11:31
 */
@CommonsLog
public class ConsumerService {
    private long pollDuration;
    protected volatile ExecutorService consumersExecutor;
    @Getter
    private TbQueueConsumer<TbQueueMsg> mainConsumer;
    private String currentIp;

    protected volatile boolean stopped = false;

    public void init(TbQueueConsumer<TbQueueMsg> mainConsumer) {
        this.consumersExecutor = Executors.newCachedThreadPool();
        this.mainConsumer = mainConsumer;
        launchMainConsumers();
        this.mainConsumer.subscribe();

    }

    public ConsumerService(long pollDuration, String currentIp) {
        this.pollDuration = pollDuration;
        this.currentIp = currentIp;
    }

    /**
     * 消费服务主线程
     */
    protected void launchMainConsumers() {
        consumersExecutor.submit(() -> {
            while (!stopped) {
                try {
                    //todo
                    List<TbQueueMsg> poll = mainConsumer.poll(pollDuration);
                    List<TbQueueMsg> msgs = poll;
                    if (msgs.isEmpty()) {
                        continue;
                    }

                    for (TbQueueMsg item : msgs) {
                        //todo
//                        }
                    }
                } catch (Exception e) {
                    log.error("Exception", e);
                }
            }
            log.info("Queue Consumer stopped.");
        });
    }


    public void destroy() {
        if (!stopped) {
            stopMainConsumers();
        }
        stopped = true;
        if (consumersExecutor != null) {
            consumersExecutor.shutdownNow();
        }

    }

    protected void stopMainConsumers() {
        if (mainConsumer != null) {
            mainConsumer.unsubscribe();
        }
    }
}
