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

import com.dji.sample.component.websocket.model.BizCodeEnum;
import com.dji.sample.component.websocket.service.IWebSocketMessageService;
import com.dji.sample.manage.model.dto.DeviceDTO;
import com.dji.sample.manage.model.dto.TelemetryDTO;
import com.dji.sample.manage.service.IDeviceRedisService;
import com.dji.sdk.cloudapi.airsense.AirsenseWarning;
import com.dji.sdk.cloudapi.airsense.api.AbstractAirsenseService;
import com.dji.sdk.mqtt.MqttReply;
import com.dji.sdk.mqtt.events.TopicEventsRequest;
import com.dji.sdk.mqtt.events.TopicEventsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 注册 {@code inboundEventsAirsenseWarning} channel，并处理机场/飞行器 AirSense 告警。
 * Demo 未提供实现时，events 路由会因 channel 缺失刷 ERROR。
 */
@Slf4j
@Service
public class SDKAirsenseService extends AbstractAirsenseService {

    @Autowired
    private IDeviceRedisService deviceRedisService;

    @Autowired
    private IWebSocketMessageService webSocketMessageService;

    @Override
    public TopicEventsResponse<MqttReply> airsenseWarning(
            TopicEventsRequest<List<AirsenseWarning>> request, MessageHeaders headers) {
        String gatewaySn = request.getGateway();
        List<AirsenseWarning> warnings = request.getData() == null
                ? Collections.emptyList() : request.getData();
        log.debug("AirSense warning from {}: count={}", gatewaySn, warnings.size());

        Optional<DeviceDTO> deviceOpt = deviceRedisService.getDeviceOnline(gatewaySn);
        if (deviceOpt.isPresent() && StringUtils.hasText(deviceOpt.get().getWorkspaceId())) {
            webSocketMessageService.sendBatch(
                    deviceOpt.get().getWorkspaceId(),
                    BizCodeEnum.AIRSENSE_WARNING.getCode(),
                    TelemetryDTO.<List<AirsenseWarning>>builder()
                            .sn(gatewaySn)
                            .host(warnings)
                            .build());
        }

        return new TopicEventsResponse<MqttReply>().setData(MqttReply.success());
    }
}
