Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.service;

import com.spice.profitmandi.common.model.MapBoxResult;
import com.spice.profitmandi.common.util.StringUtils;
import com.spice.profitmandi.common.web.client.RestClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MapBoxService {

    private static final Logger LOGGER = LogManager.getLogger(MapBoxService.class);
    private static final String MAPBOX_TOKEN = "pk.eyJ1Ijoic2R0ZWNobm9sb2d5IiwiYSI6ImNtYzk2OWpoZjEwb2cybXIyaWZ6MzRmdmkifQ._UlFPHYYtCB7FIqbNbdZhg";

    @Autowired
    private RestClient restClient;

    public String reverseGeocode(String latLng) {
        try {
            double[] coords = parseLatLng(latLng);
            double lng = coords[0];
            double lat = coords[1];
            String url = String.format(
                    "https://api.mapbox.com/geocoding/v5/mapbox.places/%f,%f.json?access_token=%s&limit=1",
                    lng, lat, MAPBOX_TOKEN
            );
            LOGGER.info("Reverse geocode URL: {}", url);
            String response = restClient.get(url, null, null);
            JSONObject json = new JSONObject(response);
            if (json.has("features") && json.getJSONArray("features").length() > 0) {
                return json.getJSONArray("features").getJSONObject(0).getString("place_name");
            }
        } catch (Exception e) {
            LOGGER.info("Error reverse geocoding: " + e.getMessage());
        }
        return null;
    }

    public MapBoxResult calculateDistanceAndETA(double lat1, double lon1, double lat2, double lon2) {
        try {
            // Mapbox requires coordinates as lng,lat`
            String coordinates = String.format("%f,%f;%f,%f", lon1, lat1, lon2, lat2);
            String url = String.format(
                    "https://api.mapbox.com/directions/v5/mapbox/driving/%s?access_token=%s",
                    coordinates, MAPBOX_TOKEN
            );

            LOGGER.info("Request URL {}", url);
            String response = restClient.get(url, null, null);

            JSONObject json = new JSONObject(response);
            JSONObject route = json.getJSONArray("routes").getJSONObject(0);

            LOGGER.info("route: {}", route);
            double distanceInMeters = route.getDouble("distance");
            double durationInSeconds = route.getDouble("duration");

            String distanceKm = StringUtils.formatDistance(distanceInMeters);

            LOGGER.info("distanceKm: {}, durationInSeconds: {}", distanceKm, durationInSeconds);
            return new MapBoxResult(distanceKm, durationInSeconds);

        } catch (Exception e) {
            LOGGER.info("Error calling Mapbox API: " + e);
            return new MapBoxResult("0.0", 0L);
        }
    }

    public MapBoxResult calculateDistanceAndETA(String latLng1, String latLng2) {
        try {
            double[] origin = parseLatLng(latLng1);
            double[] destination = parseLatLng(latLng2);

            return calculateDistanceAndETA(origin[1], origin[0], destination[1], destination[0]);

        } catch (Exception e) {
            LOGGER.info("Invalid latLng format: " + e.getMessage());
            return new MapBoxResult("0.0", 0L);
        }
    }

    private static double[] parseLatLng(String latLng) {
        String[] parts = latLng.split(",");
        if (parts.length != 2) throw new IllegalArgumentException("Invalid format: " + latLng);

        double lat = Double.parseDouble(parts[0].trim());
        double lon = Double.parseDouble(parts[1].trim());

        return new double[]{lon, lat};
    }
}