package com.jay.monitor.data.client.ext;

import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
import com.jay.monitor.data.core.model.serializable.base.JsonTextData;
import com.jay.monitor.data.core.model.serializable.base.SearchIndexData;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * @Module 规则工厂
 * @Description 规则工厂
 * @Author liukaixiong
 * @Date 2020/11/23 20:39
 */
@Component
public class MonitorRuleFactory implements InitializingBean {

    @Autowired(required = false)
    private List<MonitorRuleCallback> monitorRuleCallbacks;

    private Map<String, BiConsumer<String, ? super BaseDTO>> ruleMap = new HashMap<>();

    /**
     * 应用规则数据
     *
     * @param key     规则key
     * @param baseDTO 监控生成基础数据
     */
    public void applyRule(BaseDTO baseDTO, String key) {
        if (baseDTO instanceof JsonTextData && baseDTO instanceof SearchIndexData) {
            if (ruleMap != null) {
                JsonTextData jsonTextData = (JsonTextData) baseDTO;
                if (!StringUtils.isEmpty(jsonTextData.getJsonContent())) {
                    // 默认通用的数据处理
                    BiConsumer<String, ? super BaseDTO> consumer = ruleMap.get(MonitorRuleCallback.allMatchRuleType);
                    if (consumer != null) {
                        consumer.accept(jsonTextData.getJsonContent(), baseDTO);
                    }

                    consumer = ruleMap.get(key);
                    if (consumer != null) {
                        consumer.accept(jsonTextData.getJsonContent(), baseDTO);
                    }
                }
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        builderMqMap();
    }

    /**
     * 构建所有规则
     */
    private void builderMqMap() {
        if (monitorRuleCallbacks != null) {
            for (MonitorRuleCallback monitorRuleCallback : monitorRuleCallbacks) {
                monitorRuleCallback.registerRule(ruleMap);
            }
        }
    }
}
