package org.jim.server.command.handler.processor.chat;

import org.jim.common.ImConst;
import org.jim.common.packets.Command;
import org.jim.common.packets.Group;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.ChatReqHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.utils.thread.pool.AbstractQueueRunnable;

import java.util.concurrent.Executor;

/**
 * @author Darren
 * @date 2020/2/11 9:31
 */
public class IMAutoMsgQueueRunnable extends AbstractQueueRunnable<Group> {

    private static Logger log = LoggerFactory.getLogger(IMAutoMsgQueueRunnable.class);

    private IMAutoMessageProcessor iMAutoMessageProcessor;

    public IMAutoMsgQueueRunnable(Executor executor) {
        super(executor);
        ChatReqHandler chatReqHandler = CommandManager.getCommand(Command.COMMAND_CHAT_REQ,ChatReqHandler.class);
        iMAutoMessageProcessor = chatReqHandler.getProcessor(ImConst.IM_AUTO_MESSAGE_PROCESSOR, IMAutoMessageProcessor.class).get(0);
    }

    @Override
    public boolean addMsg(Group group) {
        if(this.isCanceled()){
            log.error("任务已经取消，添加到消息队列失败");
            return false;
        }
        return msgQueue.add(group);
    }

    @Override
    public void runTask() {
        int size = msgQueue.size();
        if(size < 0){
            return ;
        }
        Group group = null;
        //ConcurrentLinkedQueue 中 poll() 方法:
        //检索并删除此队列的头部，如果此队列为空，则返回 null
        while( (group = msgQueue.poll()) != null ){
            if(iMAutoMessageProcessor != null){
                iMAutoMessageProcessor.handler(group);
            }
        }
    }

}
