package cn.ibizlab.core.extensions.util;

import cn.ibizlab.core.extensions.domain.EngineMQMsg;
import cn.ibizlab.core.extensions.domain.LocalMsgEvent;
import cn.ibizlab.core.extensions.domain.ResultsMQMsg;
import cn.ibizlab.core.rule.domain.ExecResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.jobs.model.JobsInfo;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@ConditionalOnExpression("(!${rocketmq.producer.enabled:false})&&(!${rocketmq.consumer.enabled:false})")
public class LocalMsgProducerService implements MsgProducerService{
    @Autowired
    protected Disruptor<LocalMsgEvent> disruptor;

    @Override
    public void sendEngineMsg(EngineMQMsg engineMQMsg) throws Exception {
        LocalMsgEvent localMsgEvent = new LocalMsgEvent();
        localMsgEvent.setMessage(engineMQMsg);
        localMsgEvent.setTags("Engine");
        if (log.isDebugEnabled()) {
            log.debug("EngineMQMsg Event Send: {}", engineMQMsg.getBatch());
        }
        disruptor.publishEvent((event, sequence, bind) -> {event.setBody(bind.getBody());event.setTags(localMsgEvent.getTags());}, localMsgEvent);
    }

    @Override
    public void sendBuildMsg(EngineMQMsg engineMQMsg) throws Exception {
        LocalMsgEvent localMsgEvent = new LocalMsgEvent();
        localMsgEvent.setMessage(engineMQMsg);
        localMsgEvent.setTags("Build");
        if (log.isDebugEnabled()) {
            log.debug("BuildMQMsg Event Send: {}", engineMQMsg.getBatch());
        }
        disruptor.publishEvent((event, sequence, bind) -> {event.setBody(bind.getBody());event.setTags(localMsgEvent.getTags());}, localMsgEvent);
    }

    @Override
    public void sendResultsMsg(ResultsMQMsg resultsMQMsg) throws Exception {
        LocalMsgEvent localMsgEvent = new LocalMsgEvent();
        localMsgEvent.setMessage(resultsMQMsg);
        if (log.isDebugEnabled()) {
            log.debug("ResultsMQMsg Event Send: {}", resultsMQMsg.getKeyValueField());
        }
        disruptor.publishEvent((event, sequence, bind) -> event.setBody(bind.getBody()), localMsgEvent);
    }

    @Override
    public void sendRuleResultsMsg(String topic, String tags,List<ExecResult> listExecResultMsg) throws Exception {
        log.error("RuleResultsMQMsg 不支持非MQ模式发送规则结果至消息队列！数据集合：{} 主题：topic: {}, tags：{}",JSON.toJSONString(listExecResultMsg),topic,tags);
    }
}
