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
//                        Message innerMsg = new Message();
//                        TbQueueMsgHeaders headMap = item.getHeaders();
//                        int messageProtocl = headMap.get(MessageHeader.MESSAGEPROTOCOL)[0];
//                        Map<String, Object> headers = new HashMap<>();
//                        innerMsg.setPayload(item.getData());
//                        headers.put(MessageHeader.MESSAGEPROTOCOL, messageProtocl);
//                        innerMsg.setStoreTime(DateUtils.getCurrDate().getTime());
//                        if(messageProtocl== MsgTypeEnum.MSG_SYSTEM.getValue()){
//                            innerMsg.setHeaders(headers);
//                            sendSysMessage2Cluster(innerMsg);
//                        }else{
//                            String clientId = MixAll.convertByteS2Str(headMap.get(MessageHeader.CLIENTID));
//                            int messageType = headMap.get(MessageHeader.MESSAGETYPE)[0];
//                            String topic = MixAll.convertByteS2Str(headMap.get(MessageHeader.TOPIC));
//                            int qos = headMap.get(MessageHeader.QOS)[0];
//
//                            innerMsg.setClientId(clientId);
//                            innerMsg.setType(Message.Type.valueOf(messageType));
//                            headers.put(MessageHeader.TOPIC, topic);
//                            headers.put(MessageHeader.QOS, qos);
//                            headers.put(MessageHeader.RETAIN, false);
//                            headers.put(MessageHeader.DUP, false);
//                            innerMsg.setHeaders(headers);
//                            sendContrlMessage2Cluster(innerMsg);
//                        }
                    }
                } 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();
        }
    }
}
