package com.dji.sample.ai.service.impl;

import com.dji.sample.ai.model.entity.AiInfoEntity;
import com.dji.sample.ai.service.IAiInfoService;
import com.dji.sdk.common.Common;
import com.dji.sdk.mqtt.ai.AbstractAiInfoService;
import com.dji.sdk.mqtt.ai.TopicAiInfoResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

/**
 * @author guan
 */
@Service
public class SdkAiInfoServiceImpl extends AbstractAiInfoService {

    @Autowired
    IAiInfoService aiInfoService;
    /**
     * Handle the reply message from topic "/ai_info".
     * @param message   reply message
     * @throws IOException
     */
    @Override
    public void aiInfo(Message<?> message) throws IOException {

        MessageHeaders headers = message.getHeaders();
        String topic = Objects.requireNonNull(headers.get(MqttHeaders.RECEIVED_TOPIC)).toString();
        byte[] payload = (byte[])message.getPayload();

        JsonNode jsonData = Common.getObjectMapper().readValue(payload, new TypeReference<>() {});
        // 转换数据
//        TopicAiInfoResponse<JsonNode> receiver = Common.getObjectMapper().readValue(payload, new TypeReference<>() {});
//        JsonNode jsonData = receiver.getData();
        // 进行操作
        AiInfoEntity aiInfoEntity = new AiInfoEntity();
        // 保存数据库
        aiInfoEntity.setCreateTime(System.currentTimeMillis());
        aiInfoEntity.setDeviceSn(jsonData.get("device_sn").asText());
        aiInfoEntity.setPayloadSn(jsonData.get("payload_sn").asText());
        aiInfoEntity.setWarnType(jsonData.get("warn_type").asText());
        aiInfoEntity.setWarnEvent(jsonData.get("warn_event").asText());
        aiInfoEntity.setWarnTime(jsonData.get("warn_time").asLong());
        aiInfoEntity.setImageUrl(jsonData.get("image_url").asText());
        aiInfoEntity.setWarnLocation(jsonData.get("warn_location").asText());
        aiInfoEntity.setAlgorithmType(jsonData.get("algorithm_type").asText());
        JsonNode obj = jsonData.get("obj");
        if (obj != null) {
            aiInfoEntity.setJson(obj.toString());
        }

        aiInfoService.save(aiInfoEntity);
    }
}
