package com.jay.monitor.data.server.report.alert.rule;

import com.jay.monitor.data.core.enums.MsgTypeEnums;
import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
import com.jay.monitor.data.core.model.serializable.base.RequestDataData;
import com.jay.monitor.data.server.enums.AlertRuleEnums;
import com.jay.monitor.data.server.models.config.AlertRuleConfigModel;
import com.jay.monitor.data.server.store.ConfigStoreManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Module 告警规则
 * @Description 请求时长告警规则
 * @Author liukaixiong
 * @Date 2021/1/14 10:49
 */
@Component
public class RequestTimeAlertRule implements AlertRule {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ConfigStoreManager configStoreManager;

    @Override
    public AlertRuleEnums ruleType() {
        return AlertRuleEnums.REQUEST_TIME;
    }

    @Override
    public boolean isTrigger(BaseDTO baseDTO) {

        if (!configStoreManager.alertEnable()) {
            return false;
        }

        if (baseDTO instanceof RequestDataData) {
            MsgTypeEnums type = baseDTO.getType();
            RequestDataData requestData = (RequestDataData) baseDTO;
            Long requestTime = requestData.getRequestTime();
            if (requestTime != null) {
                AlertRuleConfigModel alertConfigModel = configStoreManager.getAlertRuleConfigModel(type);
                if (alertConfigModel != null) {
                    Integer maxTime = alertConfigModel.getMaxTime();
                    if (requestTime >= maxTime) {
                        return true;
                    }
                }
            } else {
                logger.debug("not fond request time !");
            }
        }
        return false;
    }

}
