package com.ningdatech.carapi.scheduler.util;

import com.alibaba.fastjson.JSONObject;
import com.ningdatech.carapi.common.constant.GPSDataEnum;
import com.ningdatech.carapi.scheduler.contants.TaskConstant;
import com.ningdatech.carapi.scheduler.entity.GpsData;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;

/**
 * @author CMM
 * @description
 * @since 2022/12/07 15:23
 */
public class GpsUtils {

    private GpsUtils() {
    }

    public static GpsData getGpsData(JSONObject gpsJson) {
        GpsData gpsData = new GpsData();
        BigDecimal altitudeTemp = gpsJson.getBigDecimal(GPSDataEnum.ALTITUDE.getDesc());
        Optional<BigDecimal> altitudeBigDecimal = Optional.ofNullable(altitudeTemp).map(a -> a.divide(TaskConstant.Math.ALTITUDE_UNITS, RoundingMode.HALF_UP));
        if (altitudeBigDecimal.isPresent()) {
            BigDecimal altitude = altitudeBigDecimal.get().setScale(2, RoundingMode.HALF_UP);
            gpsData.setAltitude(altitude);
        }

        BigDecimal longitudeTemp = gpsJson.getBigDecimal(GPSDataEnum.LONGITUDE.getDesc());
        Optional<BigDecimal> longitudeOptional = Optional.ofNullable(longitudeTemp).map(l -> l.divide(TaskConstant.Math.LONGITUDE_UNITS, RoundingMode.HALF_UP));
        if (longitudeOptional.isPresent()) {
            BigDecimal longitude = longitudeOptional.get().setScale(6, RoundingMode.HALF_UP);
            gpsData.setLongitude(longitude);
        }
        BigDecimal latitudeTemp = gpsJson.getBigDecimal(GPSDataEnum.LATITUDE.getDesc());
        Optional<BigDecimal> latitudeOptional = Optional.ofNullable(latitudeTemp).map(l -> l.divide(TaskConstant.Math.LONGITUDE_UNITS, RoundingMode.HALF_UP));
        if (latitudeOptional.isPresent()) {
            BigDecimal latitude = latitudeOptional.get().setScale(6, RoundingMode.HALF_UP);
            gpsData.setLatitude(latitude);
        }
        BigDecimal speedTemp = gpsJson.getBigDecimal(GPSDataEnum.SPEED.getDesc());
        Optional<BigDecimal> speedOptional = Optional.ofNullable(speedTemp).map(s -> s.multiply(TaskConstant.Math.SPEED_UNITS));
        if (speedOptional.isPresent()) {
            BigDecimal speed = speedOptional.get().setScale(2, RoundingMode.HALF_UP);
            gpsData.setSpeed(speed);
        }

        BigDecimal directionTemp = gpsJson.getBigDecimal(GPSDataEnum.DIRECTION.getDesc());
        Optional<BigDecimal> directionOptional = Optional.ofNullable(directionTemp).map(s -> s.divide(TaskConstant.Math.DIRECTION_UNITS, RoundingMode.HALF_UP));
        if (directionOptional.isPresent()) {
            BigDecimal direction = directionOptional.get().setScale(2, RoundingMode.HALF_UP);
            gpsData.setDirection(direction);
        }
        return gpsData;
    }
}
