package cn.ibizlab.core.extensions.util;

import cn.ibizlab.core.extensions.cql.ExecResultRepository;
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.extensions.service.DABuildExService;
import cn.ibizlab.core.extensions.service.RuleEngineExService;
import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
public class LocalMsgEventHandler implements EventHandler<LocalMsgEvent> {

    @Autowired
    @Lazy
    private RuleEngineExService ruleEngineExService;

    @Autowired
    @Lazy
    private DABuildExService daBuildExService;

    @Autowired(required = false)
    @Lazy
    private ExecResultRepository execResultRepository;

    @Override
    public void onEvent(LocalMsgEvent localMsgEvent, long sequence, boolean endOfBatch) throws Exception {
        if (localMsgEvent.getType()==1) {
            String tags = localMsgEvent.getTags();
            if("Engine".equalsIgnoreCase(tags)) {
                EngineMQMsg engineMQMsg = localMsgEvent.getMessage(EngineMQMsg.class);
                if (log.isDebugEnabled()) {
                    log.debug("EngineMQMsg Event Handler: {}", engineMQMsg.getBatch());
                }
                ruleEngineExService.processData(engineMQMsg);
            }else if("Build".equalsIgnoreCase(tags)){
                EngineMQMsg engineMQMsg = localMsgEvent.getMessage(EngineMQMsg.class);
                if (log.isDebugEnabled()) {
                    log.debug("BuildMQMsg Event Handler: {}", engineMQMsg.getBatch());
                }
                daBuildExService.processData(engineMQMsg);
            }
        }
        else if (localMsgEvent.getType()==2) {

            ResultsMQMsg resultsMQMsg = localMsgEvent.getMessage(ResultsMQMsg.class);
            if (log.isDebugEnabled()) {
                log.debug("ResultsMQMsg Event Handler: {}", resultsMQMsg.getKeyValueField());
            }

            if(!StringUtils.isEmpty(resultsMQMsg.getKeyValueField()))
                execResultRepository.saveResultsMQMsg(resultsMQMsg);
        }
    }
}
