package com.ruoyi.dj.mqtt.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.dj.mqtt.client.DJICloudMQTTClient;
import com.ruoyi.dj.mqtt.common.CommonFields;
import com.ruoyi.dj.mqtt.common.CommonFieldsVo;
import com.ruoyi.dj.mqtt.common.CommonResponse;
import com.ruoyi.dj.mqtt.utils.CommonFieldsVoUtil;
import com.ruoyi.dj.mqtt.utils.GatewayOperationLogUtil;
import com.ruoyi.dj.mqtt.utils.ParseMethodUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class ServicesReplyHandler {

    @Autowired
    private DJICloudMQTTClient djiCloudMQTTClient;

    ObjectMapper objectMapper = new ObjectMapper();

    public void handle(String matchedPart, String message) {
        CommonFieldsVo commonFieldsVo = CommonFieldsVoUtil.extractCommonFields(message);
        if (commonFieldsVo != null) {
            CommonResponse commonResponse = ParseMethodUtil.parseMethod(message);
            if (commonResponse.getMethod().equals("flighttask_prepare")) {
                log.info("下发任务的回复:{}", message);
            }
            if (commonResponse.getMethod().equals("flighttask_execute")) {
                log.info("service_reply 的 flighttask_execute,{}", message);
            }
            CompletableFuture<String> responseFuture = djiCloudMQTTClient.getResponseFuture(commonFieldsVo);
            if (responseFuture != null) {
                responseFuture.complete(message);
                djiCloudMQTTClient.completeResponseFuture(commonFieldsVo, message);
            } else {
                log.warn("未找到匹配 Services Reply 的响应处理器，tid: {}, method: {}", commonFieldsVo.getTid(), commonFieldsVo.getMethod());
            }
        } else {
            log.error("提取 CommonFields 失败，消息: " + message);
        }
    }
}
