package com.aros.apron.tools;

import android.util.Log;

import com.aros.apron.base.BaseManager;
import com.aros.apron.entity.MissionDataBean;
import com.aros.apron.entity.Movement;
import com.aros.apron.manager.TakeOffToPointManager;
import com.dji.wpmzsdk.common.data.Template;
import com.dji.wpmzsdk.manager.WPMZManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import dji.sdk.keyvalue.key.FlightControllerKey;
import dji.sdk.keyvalue.key.KeyTools;
import dji.sdk.keyvalue.value.common.LocationCoordinate3D;
import dji.sdk.wpmz.value.mission.*;
import dji.v5.manager.KeyManager;

/**
 * 单航点起飞→目标点→返航
 * 纯 Java、无 Builder、无 WaypointHeadingParam
 */
public class Generakmztools extends BaseManager {
    private Generakmztools() {}
    private static class Holder { private static final Generakmztools INSTANCE = new Generakmztools(); }
    public static Generakmztools getInstance() { return Holder.INSTANCE; }

    public Boolean generateKmz(MissionDataBean data) {
        sendEvent2Server("开始生成一键起飞航线", 1);
        LocationCoordinate3D lat = KeyManager.getInstance().getValue(KeyTools.createKey(FlightControllerKey.
                KeyAircraftLocation3D));

        if (lat == null) {
            LogUtil.log("qwq", "当前位置为空，无法生成航线");
            sendEvent2Server("生成失败：未获取到飞机当前位置", 1);
            return false;
        }
        if (lat.getLatitude() == null || lat.getLongitude() == null|| lat.getAltitude() == null) {
            LogUtil.log("qwq", "当前位置坐标无效");
            sendEvent2Server("生成失败：位置坐标无效", 1);
            return false;
        }

        File root = new File("/storage/self/primary/DJIDemo/cache/kmz");
        if (!root.exists()) root.mkdirs();
        File kmz = new File(root, "takeofftopoint.kmz");

        /* 1. <wpml:mission> 基本信息 */
        WaylineMission mission = new WaylineMission();
        mission.setAuthor("aros");
        double now = System.currentTimeMillis();
        mission.setCreateTime(now);
        mission.setUpdateTime(now);

        /* 2. <wpml:missionConfig> 全局策略 */
        WaylineMissionConfig config = new WaylineMissionConfig();
        //飞向目标点的模式
        config.setFlyToWaylineMode(WaylineFlyToWaylineMode.SAFELY);
        //航线结束后的动作
        config.setFinishAction(WaylineFinishedAction.NO_ACTION);
        if(data.getCommanderModeLostAction()==0){
            //继续
            config.setExitOnRCLostBehavior(WaylineExitOnRCLostBehavior.GO_ON);
        }else if(data.getCommanderModeLostAction()==1){
            //失控退出航线
            config.setExitOnRCLostBehavior(WaylineExitOnRCLostBehavior.EXCUTE_RC_LOST_ACTION);
        }
        //失控退出航线的动作
        if(data.getRcLostAction()==0){
            //悬停
            config.setExitOnRCLostType(WaylineExitOnRCLostAction.HOVER);
        } else if (data.getRcLostAction()==1) {
            //精确着陆
            config.setExitOnRCLostType(WaylineExitOnRCLostAction.LANDING);
        } else if (data.getRcLostAction()==2) {
            //返航
            config.setExitOnRCLostType(WaylineExitOnRCLostAction.GO_BACK);
        }
        //全局过度速度
        config.setGlobalTransitionalSpeed((double)data.getMaxSpeed());
        //全局返航高度
        config.setGlobalRTHHeight((double)data.getRthAltitude());
        config.setIsGlobalRTHHeightSet(true);
        //安全起飞高度
        config.setSecurityTakeOffHeight((double)data.getSecurityTakeoffHeight());
        config.setIsSecurityTakeOffHeightSet(true);



        //为400准备的
        WaylineDroneInfo droneInfo = new WaylineDroneInfo();
        droneInfo.setDroneType(WaylineDroneType.PM440);
        config.setDroneInfo(droneInfo);


        //这个航点列表
        WaylineWaypoint wp1 = new WaylineWaypoint();
        WaylineWaypoint wp = new WaylineWaypoint();

        //初始点
        wp1.setWaypointIndex(0);
        wp1.setLocation(new WaylineLocationCoordinate2D(lat.getLatitude(), lat.getLongitude()));
        //wp1.setHeight((double)data.getCommanderFlightHeight());
        wp1.setHeight(data.getTargetHeight()- Movement.getInstance().getHeight());
       // wp1.setUseGlobalFlightHeight(true);
        //椭球高
        wp1.setEllipsoidHeight(data.getTargetHeight()- Movement.getInstance().getHeight());
        wp1.setUseStraightLine(true);
        wp1.setUseGlobalTurnParam(true);
        wp1.setUseGlobalYawParam(true);
        wp1.setUseGlobalGimbalHeadingParam(true);
        wp1.setUseGlobalAutoFlightSpeed(true);
        wp1.setIsRisky(false);



        //基础设置
        wp.setWaypointIndex(1);
        wp.setLocation(new WaylineLocationCoordinate2D(data.getTargetLatitude(), data.getTargetLongitude()));
        //wp.setHeight((double)data.getCommanderFlightHeight());
        wp.setHeight(data.getTargetHeight()- Movement.getInstance().getHeight());
       // wp.setUseGlobalFlightHeight(true);
        //椭球高
        wp.setEllipsoidHeight(data.getTargetHeight()- Movement.getInstance().getHeight());
        wp.setUseStraightLine(true);
        wp.setUseGlobalTurnParam(true);
        wp.setUseGlobalYawParam(true);
        wp.setUseGlobalGimbalHeadingParam(true);
        wp.setUseGlobalAutoFlightSpeed(true);
        wp.setIsRisky(false);


        List<WaylineWaypoint> wpList = new ArrayList<>();
        wpList.add(wp1);
        wpList.add(wp);

        /* 4. <wpml:waypointInfo> */
        WaylineTemplateWaypointInfo waypointInfo = new WaylineTemplateWaypointInfo();

        waypointInfo.setGlobalFlightHeight(data.getTargetHeight());
        waypointInfo.setIsGlobalFlightHeightSet(true);

        WaylineWaypointYawParam waypointYawParam=new WaylineWaypointYawParam();
        waypointYawParam.setYawMode(WaylineWaypointYawMode.FOLLOW_WAYLINE);
        waypointInfo.setGlobalYawParam(waypointYawParam);
        waypointInfo.setIsTemplateGlobalYawParamSet(true);

        WaylineWaypointGimbalHeadingParam waypointGimbalHeadingParam=new WaylineWaypointGimbalHeadingParam();
        waypointGimbalHeadingParam.setHeadingMode(WaylineWaypointGimbalHeadingMode.FOLLOW_WAYLINE);
        waypointGimbalHeadingParam.setYawAngle(0.0);
        waypointGimbalHeadingParam.setPitchAngle(0.0);
        waypointInfo.setGlobalGimbalHeadingParam(waypointGimbalHeadingParam);

        waypointInfo.setGlobalTurnMode(WaylineWaypointTurnMode.COORDINATE_TURN);
        waypointInfo.setIsTemplateGlobalTurnModeSet(true);
        waypointInfo.setWaypoints(wpList);

        waypointInfo.setUseStraightLine(true);



        /* 5. <wpml:coordinateParam> */
        WaylineCoordinateParam coordParam = new WaylineCoordinateParam();
        coordParam.setCoordinateMode(WaylineCoordinateMode.WGS84);
        coordParam.setAltitudeMode(WaylineAltitudeMode.RELATIVE_TO_START_POINT);
        coordParam.setPositioningType(WaylinePositioningType.GPS);

        /* 6. <wpml:template> */
        Template template = new Template();
        template.setTemplateId(0);
        template.setCoordinateParam(coordParam);
        template.setTransitionalSpeed((double)data.getMaxSpeed());
        template.setWaypointInfo(waypointInfo);
        template.setUseGlobalTransitionalSpeed(true);
        template.setAutoFlightSpeed((double)data.getMaxSpeed());

        //不写就报错
        template.setPayloadParam(new ArrayList<>());
        /* 7. 生成文件 */
        WPMZManager.getInstance().generateKMZFile(kmz.getAbsolutePath(), mission, config, template);
        //验证这个kmz

        WaylineCheckErrorMsg result= WPMZManager.getInstance().checkValidation(kmz.getAbsolutePath());
        LogUtil.log("qwq",result.toString());
        if (result.getValue().isEmpty()) {
            LogUtil.log("qwq", "KMZ 校验通过");
            sendEvent2Server("一键起飞航线文件生成成功", 1);
            return true;
        } else {
            // 其他错误码照旧报错
            LogUtil.log("qwq", "校验失败，错误码：" + result.getValue());
            sendEvent2Server("一键起飞航线文件生成失败错误码："+result.getValue(), 1);
            return false;
        }
    }
}