package com.elab.log.ext;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.elab.log.model.CatCrossIdModel;
import com.jay.monitor.data.client.ext.MonitorRuleCallback;
import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
import com.jay.monitor.data.core.model.serializable.base.TranceLogData;

import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 消息监控规则
 *
 * @author liukaixong
 */
public class CatIdMonitorRule implements MonitorRuleCallback {

    @Override
    public void registerRule(Map<String, BiConsumer<String, ? super BaseDTO>> ruleMap) {
        ruleMap.put(MonitorRuleCallback.allMatchRuleType, (value, mqData) -> {
            if (mqData instanceof TranceLogData) {
                CatCrossIdModel catCrossIdModel = JSON.parseObject(value, CatCrossIdModel.class);
                TranceLogData tranceLogData = (TranceLogData) mqData;
                if (catCrossIdModel.get_catRootMessageId() != null) {
                    tranceLogData.setRootLogId(catCrossIdModel.get_catRootMessageId());
                    tranceLogData.setParentLogId(catCrossIdModel.get_catParentMessageId());
                }
                // 这里不用get_catChildMessageId的原因是因为生产者是不确定下游的消费者是谁的。
                // 这里还是用当前线程产生的LogId。这个id非常重要。
                tranceLogData.setLogId(Cat.getCurrentMessageId());
            }
        });
    }
}