package com.jay.monitor.data.client;

import com.jay.monitor.data.client.ext.MonitorRuleFactory;
import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Module 监控发送
 * @Description 监控发送器
 * @Author liukaixiong
 * @Date 2020/10/23 19:38
 */
@Component
public class MonitorSendProducer implements ApplicationContextAware, InitializingBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static ApplicationContext applicationContext;
    private static volatile boolean isEnableProducer = false;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MonitorSendProducer.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MonitorDataClient monitorData = getMonitorData();
        if (monitorData != null) {
            isEnableProducer = true;
            logger.info("开启监控数据传输器 : " + monitorData.getAddr());
        }
    }

    /**
     * 发送数据
     *
     * @param dataDTO
     * @throws Exception
     */
    public static void sendMsg(BaseDTO dataDTO) {
        sendMsg(null, dataDTO);
    }

    /**
     * 发送消息
     *
     * @param ruleKey 规则标识 -> 如果有该规则则会回到用户拓展的类 具体参考:MonitorRuleCallback实现
     * @param baseDTO 监控发送数据
     */
    public static void sendMsg(String ruleKey, BaseDTO baseDTO) {
        if (isEnableProducer) {
            if (!StringUtils.isEmpty(ruleKey)) {
                applyRule(ruleKey, baseDTO);
            }
            getMonitorData().sendObjectMsg(baseDTO);
        }
    }

    private static void applyRule(String ruleKey, BaseDTO baseDTO) {
        MonitorRuleFactory ruleFactory = getMonitorRuleFactory();
        if (ruleFactory != null) {
            ruleFactory.applyRule(baseDTO, ruleKey);
        }
    }

    private static MonitorRuleFactory getMonitorRuleFactory() {
        try {
            return applicationContext.getBean(MonitorRuleFactory.class);
        } catch (Exception e) {

        }
        return null;
    }

    public static MonitorDataClient getMonitorData() {
        try {
            return applicationContext.getBean(MonitorDataClient.class);
        } catch (Exception e) {
            return null;
        }
    }
}
