package com.dji.sdk.mqtt.osd;

import com.dji.sdk.cloudapi.device.PayloadModelConst;
import com.dji.sdk.common.Common;
import com.dji.sdk.common.SDKManager;
import com.dji.sdk.config.version.GatewayManager;
import com.dji.sdk.config.version.GatewayTypeEnum;
import com.dji.sdk.exception.CloudSDKException;
import com.dji.sdk.mqtt.ChannelName;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.dji.sdk.mqtt.TopicConst.*;

/**
 *
 * @author sean.zhou
 * @date 2021/11/17
 * @version 0.1
 */
@Configuration
public class OsdRouter {

    private static final Logger log = LoggerFactory.getLogger(OsdRouter.class);

    @Bean
    public IntegrationFlow osdRouterFlow() {
        return IntegrationFlows
                .from(ChannelName.INBOUND_OSD)
                .transform(Message.class, source -> {
                    try {
                        TopicOsdRequest response = Common.getObjectMapper().readValue((byte[]) source.getPayload(), new TypeReference<TopicOsdRequest>() {});
                        String topic = String.valueOf(source.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
                        return response.setFrom(topic.substring((THING_MODEL_PRE + PRODUCT).length(), topic.indexOf(OSD_SUF)));
                    } catch (IOException e) {
                        throw new CloudSDKException(e);
                    }
                }, null)
                .<TopicOsdRequest>handle((response, headers) -> {
                    Map<String, Object> data = (Map<String, Object>) response.getData();
                    boolean isGateway = response.getFrom().equals(response.getGateway());
                    GatewayTypeEnum gatewayType = resolveGatewayType(response.getGateway(), isGateway, data);
                    OsdDeviceTypeEnum typeEnum = OsdDeviceTypeEnum.find(gatewayType, isGateway);
                    if (!typeEnum.isGateway()) {
                        List payloadData = (List) data.getOrDefault(PayloadModelConst.PAYLOAD_KEY, new ArrayList<>());
                        PayloadModelConst.getAllIndexWithPosition().stream().filter(data::containsKey)
                                .map(data::get).forEach(payloadData::add);
                        data.put(PayloadModelConst.PAYLOAD_KEY, payloadData);
                    }
                    return response.setData(Common.getObjectMapper().convertValue(data, typeEnum.getClassType()));
                })
                .<TopicOsdRequest, OsdDeviceTypeEnum>route(response -> OsdDeviceTypeEnum.find(response.getData().getClass()),
                        mapping -> Arrays.stream(OsdDeviceTypeEnum.values()).forEach(key -> mapping.channelMapping(key, key.getChannelName())))
                .get();
    }

    /**
     * 优先用已注册网关类型；未注册时（重启后 status 尚未回来）仅按 OSD 字段推断，
     * 不调用 registerDevice(null thingVersion)，避免 CloudSDKVersionException。
     * 正式注册交给 osd* 里的 recoverDeviceOnline / update_topo。
     */
    private GatewayTypeEnum resolveGatewayType(String gatewaySn, boolean isGateway, Map<String, Object> data) {
        return SDKManager.findDeviceSDK(gatewaySn)
                .map(GatewayManager::getType)
                .orElseGet(() -> {
                    GatewayTypeEnum inferred = inferGatewayType(data, isGateway);
                    log.debug("OSD from unregistered gateway {}, infer type {}", gatewaySn, inferred);
                    return inferred;
                });
    }

    private static GatewayTypeEnum inferGatewayType(Map<String, Object> data, boolean isGatewayPayload) {
        boolean looksLikeDock = data.containsKey("drone_in_dock")
                || data.containsKey("cover_state")
                || data.containsKey("flighttask_step_code")
                || data.containsKey("drone_charge_state")
                || data.containsKey("air_conditioner")
                || data.containsKey("job_number")
                || data.containsKey("backup_battery")
                || data.containsKey("alternate_land_point");
        if (looksLikeDock || !isGatewayPayload) {
            return GatewayTypeEnum.DOCK2;
        }
        return GatewayTypeEnum.RC;
    }

}
