package com.fuyuanshen.global.mqtt.base;

import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * MQTT消息引擎
 */
@Component
public class NewMqttRuleEngine {

//    @Autowired
//    @Qualifier("threadPoolTaskExecutor")
//    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private final LinkedHashMap<String, NewMqttMessageRule> rulesMap = new LinkedHashMap<>();
    public NewMqttRuleEngine(List<NewMqttMessageRule> rules) {
        // 按优先级排序
        rules.sort(Comparator.comparing(NewMqttMessageRule::getPriority));
        rules.forEach(rule -> rulesMap.put(rule.getCommandType(), rule)
        );
    }
    
    /**
     * 执行匹配
     * @param context 处理上下文
     * @return
     */
    public boolean executeRule(NewMqttRuleContext context) {
        String commandType = context.getCommandType();
//        String funcType = context.getFuncType();
        NewMqttMessageRule mqttMessageRule = rulesMap.get(commandType);
        if (mqttMessageRule != null) {
//            threadPoolTaskExecutor.execute(() -> mqttMessageRule.execute(context));
            mqttMessageRule.execute(context);
            return true;
        }
        
        return false;
    }
}
