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

import com.dji.sample.common.util.SpringBeanUtilsTest;
import com.dji.sample.control.model.param.DronePayloadParam;
import com.dji.sample.manage.model.dto.DeviceDTO;
import com.dji.sample.manage.service.IDevicePayloadService;
import com.dji.sample.manage.service.IDeviceRedisService;
import com.dji.sdk.cloudapi.device.DeviceDomainEnum;
import com.dji.sdk.cloudapi.device.OsdCamera;
import com.dji.sdk.cloudapi.device.OsdDockDrone;
import com.dji.sdk.cloudapi.device.OsdRcDrone;
import org.springframework.util.StringUtils;

import java.util.Optional;

import static com.dji.sample.common.util.DeviceUtil.isCustomDevice;

/**
 * @author sean
 * @version 1.4
 * @date 2023/4/23
 */
public abstract class PayloadCommandsHandler {

    DronePayloadParam param;

    OsdCamera osdCamera;

    PayloadCommandsHandler(DronePayloadParam param) {
        this.param = param;
    }

    public boolean valid() {
        return true;
    }

    public boolean canPublish(String deviceSn) {
        IDeviceRedisService redis = SpringBeanUtilsTest.getBean(IDeviceRedisService.class);

        Optional<OsdDockDrone> dockDroneOpt = redis.getDeviceOsd(deviceSn, OsdDockDrone.class);
        if (dockDroneOpt.isPresent()) {
            osdCamera = dockDroneOpt.get().getCameras().stream()
                    .filter(cam -> param.getPayloadIndex().equals(cam.getPayloadIndex().toString()))
                    .findAny()
                    .orElseThrow(() -> new RuntimeException(
                            "Did not receive osd information about the camera, please check the cache data."));
            return true;
        }

        // Pilot 飞机 OSD 为 OsdRcDrone，通常无 cameras 列表；在线即可下发负载/云台指令
        Optional<OsdRcDrone> rcDroneOpt = redis.getDeviceOsd(deviceSn, OsdRcDrone.class);
        if (rcDroneOpt.isPresent()) {
            osdCamera = null;
            return true;
        }

        throw new RuntimeException("The device is offline.");
    }

    private String checkDockOnline(String dockSn) {
        Optional<DeviceDTO> deviceOpt = SpringBeanUtilsTest.getBean(IDeviceRedisService.class).getDeviceOnline(dockSn);
        if (deviceOpt.isEmpty()) {
            throw new RuntimeException("The dock is offline.");
        }
        return deviceOpt.get().getChildDeviceSn();
    }

    private void checkDeviceOnline(String deviceSn) {
        boolean isOnline = SpringBeanUtilsTest.getBean(IDeviceRedisService.class).checkDeviceOnline(deviceSn);
        if (!isOnline) {
            throw new RuntimeException("The device is offline.");
        }
    }

    private void checkAuthority(String dockSn, String deviceSn) {
        // Pilot：飞控与负载权不区分，cloud_control_auth(flight) 即可控云台
        Optional<DeviceDTO> gatewayOpt = SpringBeanUtilsTest.getBean(IDeviceRedisService.class).getDeviceOnline(dockSn);
        if (gatewayOpt.isPresent() && DeviceDomainEnum.REMOTER_CONTROL == gatewayOpt.get().getDomain()) {
            return;
        }
        boolean hasAuthority = SpringBeanUtilsTest.getBean(IDevicePayloadService.class)
                .checkAuthorityPayload(deviceSn, param.getPayloadIndex());
        if (!hasAuthority) {
            throw new RuntimeException("The device does not have payload control authority.");
        }
    }

    public final void checkCondition(String dockSn) {
        if (!valid()) {
            throw new RuntimeException("illegal argument");
        }
        // 智测放行
        if (isCustomDevice(dockSn)) {
            return;
        }

        String deviceSn = checkDockOnline(dockSn);
        if (!StringUtils.hasText(deviceSn)) {
            throw new RuntimeException("The device is offline.");
        }
        checkDeviceOnline(deviceSn);
        checkAuthority(dockSn, deviceSn);

        if (!canPublish(deviceSn)) {
            throw new RuntimeException("The current state of the drone does not support this function, please try again later.");
        }
    }

}
