导航菜单

页面标题

页面副标题

Namma Yatri v3.3.7 - LocationUpdateService.java 源代码

正在查看: Namma Yatri v3.3.7 应用的 LocationUpdateService.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package in.juspay.mobility.app;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.service.notification.StatusBarNotification;
import androidx.core.app.m;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import in.juspay.hypersdk.data.KeyValueStore;
import in.juspay.mobility.app.MyFirebaseMessagingService;
import in.juspay.mobility.app.RemoteConfigs.MobilityRemoteConfigs;
import in.juspay.mobility.common.MobilityCommonBridge;
import in.juspay.mobility.common.services.MobilityAPIResponse;
import in.juspay.mobility.common.services.MobilityCallAPI;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

@Deprecated
public class LocationUpdateService extends Service {
    private static final String DRIVER_CURRENT_LOCATION_PRIORITY_KEY = "driver_current_location_priority";
    private static final String DRIVER_FUSED_LOCATION_PRIORITY_KEY = "driver_fused_location_priority";
    private static final String LAST_LOCATION_TIME = "LAST_LOCATION_TIME";
    private static final String LOCATION_PAYLOAD = "LOCATION_PAYLOAD";
    private static final String LOG_TAG = "LocationServices";
    static JSONObject androidVersion;
    static JSONObject batteryPercentage;
    static JSONObject deviceManufacturer;
    static JSONObject deviceModel;
    private static int finalDistance;
    private static int finalDistanceWithAcc;
    private static Boolean isDistanceCalulation;
    private static Boolean isLocationUpdating;
    static JSONObject isOnCharge;
    static JSONArray metaDataForLocation;
    static JSONObject triggerFunction;
    private static final ArrayList<UpdateTimeCallback> updateTimeCallbacks;
    com.google.android.gms.location.i calDistanceCallback;
    CancellationTokenSource cancellationTokenSource;
    private Context context;
    private String drMode;
    ExecutorService executorLocUpdate;
    com.google.android.gms.location.e fusedLocClientForDistanceCal;
    com.google.android.gms.location.e fusedLocationProviderClient;
    private String gpsMethodSwitch;
    private BroadcastReceiver internetBroadcastReceiver;
    double lastLatitudeValue;
    double lastLongitudeValue;
    com.google.android.gms.location.i locationCallback;
    private String merchantID;
    double prevLat;
    double prevLon;
    MobilityRemoteConfigs remoteConfigs;
    private Timer timer;
    private TimerTask timerTask;
    boolean updated;
    private String vVariant;
    private final String LOCATION_UPDATES = "LOCATION_UPDATES";
    final int notificationServiceId = 15082022;
    final int alertNotificationId = 1868818;
    int executorBusy = 0;
    private int delayForG = 500000;
    private int delayForT = 20000;
    private int delayForGNew = 500000;
    private int delayForTNew = 20000;
    private String driverRideStatus = "IDLE";
    private int maximumLimit = 60;
    private int pointsToRemove = 1;
    private Location prevLocation = null;
    private Location prevAccLocation = null;
    private int maximumLimitNotOnRide = 1;
    private float minDispDistanceNew = 25.0f;
    private float minDispDistance = 25.0f;
    private String rideWaypoints = null;
    private long lastCallTime = 0;
    private String currentZoneGeoHash = null;
    private boolean isSpecialpickup = false;
    private String driverId = "empty";
    private final LocalBinder binder = new LocalBinder();
    private boolean storeLocationInFile = false;
    private final String FILE_NAME = "lat_long.txt";

    public class LocalBinder extends Binder {
        public LocalBinder() {
        }

        public LocationUpdateService getService() {
            return LocationUpdateService.this;
        }
    }

    public enum LocationSource {
        CurrentLocation,
        LastLocation
    }

    public enum TriggerFunction {
        TimerTask,
        GoogleCallback
    }

    public interface UpdateTimeCallback {
        void triggerUpdateTimeCallBack(String str, String str2, String str3, String str4);
    }

    static {
        Boolean bool = Boolean.FALSE;
        isLocationUpdating = bool;
        isDistanceCalulation = bool;
        finalDistance = 0;
        finalDistanceWithAcc = 0;
        updateTimeCallbacks = new ArrayList<>();
    }

    public void callDriverCurrentLocationAPI(Location location, String str, final String str2, String str3, String str4) {
        float accuracy;
        float f = 0.0f;
        if (location != null) {
            try {
                accuracy = location.getAccuracy();
            } catch (Exception e) {
                FirebaseCrashlytics.getInstance().recordException(new Exception("Exception in callDriverCurrentLocationAPI for ID : " + this.driverId + " $ Error : " + e));
                e.printStackTrace();
                return;
            }
        } else {
            accuracy = 0.0f;
        }
        if (location != null && location.hasBearing()) {
            f = location.getBearing();
        }
        float f2 = f;
        double d = 0.0d;
        double latitude = location != null ? location.getLatitude() : 0.0d;
        double longitude = location != null ? location.getLongitude() : 0.0d;
        if (location != null && location.hasSpeed()) {
            d = location.getSpeed();
        }
        double d2 = d;
        final Handler handler = new Handler(Looper.getMainLooper());
        Context context = this.context;
        final SharedPreferences sharedPreferences = context.getSharedPreferences(context.getString(R.string.preference_file_key), 0);
        final JSONArray updateLocationPayload = updateLocationPayload(sharedPreferences);
        final double d3 = longitude;
        JSONObject locationUpdatePoints = getLocationUpdatePoints(latitude, longitude, sharedPreferences, str);
        if (locationUpdatePoints == null) {
            return;
        }
        System.out.println("NammaMeter: storeLocationInFile " + this.storeLocationInFile);
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("pt", locationUpdatePoints);
        jSONObject.put("ts", str);
        jSONObject.put("acc", accuracy);
        jSONObject.put("bear", f2);
        jSONObject.put("source", str3);
        jSONObject.put("v", d2);
        if (jSONObject.has("pt")) {
            updateLocationPayload.put(jSONObject);
            updateStorage(LOCATION_PAYLOAD, updateLocationPayload.toString());
            StringBuilder sb2 = new StringBuilder();
            sb2.append("DriverUpdateLoc Payload Created - ");
            sb2.append(updateLocationPayload);
            StringBuilder sb3 = new StringBuilder();
            sb3.append("DriverUpdateLoc Executor Status - ");
            sb3.append(this.executorLocUpdate.isShutdown());
            sb3.append(" ExecutorOffFor - ");
            sb3.append(this.executorBusy);
            sb3.append(" delayForGNew - ");
            sb3.append(this.delayForGNew);
            if (canCallAPI(this.executorLocUpdate.isShutdown())) {
                this.executorLocUpdate = Executors.newSingleThreadExecutor();
                final MobilityCallAPI mobilityCallAPI = MobilityCallAPI.getInstance(this.context);
                final double d4 = latitude;
                this.executorLocUpdate.execute(new Runnable() {
                    @Override
                    public final void run() {
                        LocationUpdateService.this.lambda$callDriverCurrentLocationAPI$2(sharedPreferences, str2, mobilityCallAPI, updateLocationPayload, d4, d3, handler);
                    }
                });
                return;
            }
            int i = 1;
            if (canCallAPI(!this.executorLocUpdate.isShutdown())) {
                int i2 = this.executorBusy;
                this.executorBusy = i2 + 1;
                if (this.delayForGNew <= 5000) {
                    i = 3;
                }
                if (i2 > i) {
                    android.util.Log.e(LOG_TAG, "Executor status is busy with - " + this.executorBusy);
                    this.executorLocUpdate.shutdownNow();
                    this.executorBusy = 0;
                }
            }
        }
    }

    private void cancelTimer() {
        try {
            System.out.println("LOCATION_UPDATE: CANCEL TIMER CALLED INSIDE");
            Timer timer = this.timer;
            if (timer != null) {
                timer.cancel();
                this.timer.purge();
            }
            TimerTask timerTask = this.timerTask;
            if (timerTask != null) {
                timerTask.cancel();
            }
            this.timer = null;
            this.timerTask = null;
            isLocationUpdating = Boolean.FALSE;
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in cancelTimer " + e));
            FirebaseAnalytics.getInstance(this).c("Exception_in_cancelTimer", (Bundle) null);
            android.util.Log.e(LOG_TAG, "Error in cancelTimer " + e);
        }
    }

    public void checkLocation() {
        if (androidx.core.content.a.checkSelfPermission(this.context, "android.permission.ACCESS_FINE_LOCATION") != 0 && androidx.core.content.a.checkSelfPermission(this.context, "android.permission.ACCESS_COARSE_LOCATION") != 0) {
            showAlertNotification();
            onDestroy();
            return;
        }
        if (!isLocationEnabled()) {
            updateDriverStatus(Boolean.FALSE);
            return;
        }
        NotificationManager notificationManager = (NotificationManager) this.context.getSystemService("notification");
        for (StatusBarNotification statusBarNotification : notificationManager.getActiveNotifications()) {
            if (statusBarNotification.getId() == 1868818) {
                notificationManager.cancel(1868818);
            }
        }
    }

    private boolean checkLocationAcc(Location location, String str) {
        return ((double) location.getAccuracy()) < Double.parseDouble(str) && location.hasSpeed() && location.getSpeed() > 1.0f;
    }

    public void checkNearByPickupZone(Location location) {
        try {
            Context context = this.context;
            SharedPreferences sharedPreferences = context.getSharedPreferences(context.getString(R.string.preference_file_key), 0);
            String valueFromStorage = getValueFromStorage("IS_RIDE_ACTIVE");
            String valueFromStorage2 = getValueFromStorage("ENABLE_SPECIAL_PICKUP_WIDGET");
            if (location == null || valueFromStorage == null || valueFromStorage2 == null || !valueFromStorage.equals("false") || !valueFromStorage2.equals("true")) {
                return;
            }
            JSONArray jSONArray = new JSONArray(sharedPreferences.getString("SPECIAL_LOCATION_LIST", null));
            GeoHash geoHash = new GeoHash();
            String encode = geoHash.encode(location.getLatitude(), location.getLongitude(), 7);
            ArrayList<String> nearbyGeohashes = geoHash.nearbyGeohashes(encode, Double.parseDouble(sharedPreferences.getString("SEARCH_SPECIAL_PICKUP_WITHIN_RADIUS", "150.0")));
            nearbyGeohashes.add(encode);
            this.currentZoneGeoHash = getValueFromStorage("CURRENT_ZONE_GEO_HASH");
            if (getValueFromStorage("CURRENT_ZONE_GEO_HASH") == null) {
                updateStorage("CURRENT_ZONE_GEO_HASH", encode);
                this.currentZoneGeoHash = encode;
            }
            int i = 0;
            boolean z = false;
            while (true) {
                if (i >= jSONArray.length()) {
                    break;
                }
                String str = (String) ((JSONArray) jSONArray.get(i)).get(0);
                boolean contains = nearbyGeohashes.contains(str);
                if (!this.currentZoneGeoHash.equals(str) && contains) {
                    this.isSpecialpickup = true;
                    showWidget(true);
                    this.currentZoneGeoHash = str;
                    updateStorage("CURRENT_ZONE_GEO_HASH", str);
                }
                if (contains) {
                    this.isSpecialpickup = true;
                    z = contains;
                    break;
                } else {
                    i++;
                    z = contains;
                }
            }
            if (z || !this.isSpecialpickup) {
                return;
            }
            this.currentZoneGeoHash = encode;
            this.isSpecialpickup = false;
            updateStorage("CURRENT_ZONE_GEO_HASH", encode);
            showWidget(false);
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in CheckNearByPickupZones " + e));
            e.printStackTrace();
        }
    }

    private LocationRequest createLocationRequest(int i, float f) {
        long j = i;
        return new LocationRequest.a(getLocationPriority(), j).d(j).h(f).a();
    }

    private Notification createNotification() {
        createNotificationChannel();
        return new m.e(this, "LOCATION_UPDATES").l("Updating").k(getString(R.string.your_location_is_being_updated)).x(Utils.getResIdentifier(this.context, Build.VERSION.SDK_INT >= 26 ? "ic_launcher_small_icon" : "ny_ic_launcher", "drawable")).u(-2).t(true).j(PendingIntent.getActivity(this, 10, getPackageManager().getLaunchIntentForPackage(this.context.getPackageName()), 67108864)).b();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel a = k3.k.a("LOCATION_UPDATES", "Location Update Service", 1);
            k3.w.a(a, "LOCATION_IS_UPDATING");
            k3.x.a(a, "3_services");
            k3.o.a((NotificationManager) getSystemService(NotificationManager.class), a);
        }
    }

    private TimerTask createTimer() {
        this.timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                LocationUpdateService.this.checkVersionMismatch();
                if (LocationUpdateService.this.timerTask == null) {
                    return;
                }
                LocationUpdateService.this.timer = new Timer();
                LocationUpdateService.this.checkLocation();
                if (LocationUpdateService.this.gpsMethodSwitch.equals("CURRENT")) {
                    LocationUpdateService.this.fetchCurrentLocationWithFallback();
                } else {
                    LocationUpdateService.this.fetchLastKnownLocation();
                }
            }
        };
        this.timerTask = timerTask;
        return timerTask;
    }

    public static void deRegisterCallback(UpdateTimeCallback updateTimeCallback) {
        updateTimeCallbacks.add(updateTimeCallback);
    }

    public void fetchCurrentLocationWithFallback() {
        this.fusedLocationProviderClient.getCurrentLocation(Utils.getLocationPriority(DRIVER_CURRENT_LOCATION_PRIORITY_KEY), this.cancellationTokenSource.getToken()).addOnSuccessListener(new OnSuccessListener() {
            public final void onSuccess(Object obj) {
                LocationUpdateService.this.lambda$fetchCurrentLocationWithFallback$3((Location) obj);
            }
        }).addOnFailureListener(new OnFailureListener() {
            public final void onFailure(Exception exc) {
                LocationUpdateService.lambda$fetchCurrentLocationWithFallback$4(exc);
            }
        });
    }

    private void fetchFreshLocationWithHighAccuracy(final SimpleDateFormat simpleDateFormat) {
        this.fusedLocationProviderClient.getCurrentLocation(100, this.cancellationTokenSource.getToken()).addOnSuccessListener(new OnSuccessListener() {
            public final void onSuccess(Object obj) {
                LocationUpdateService.this.lambda$fetchFreshLocationWithHighAccuracy$5(simpleDateFormat, (Location) obj);
            }
        }).addOnFailureListener(new C0669v());
    }

    public void fetchLastKnownLocation() {
        this.fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener() {
            public final void onSuccess(Object obj) {
                LocationUpdateService.this.lambda$fetchLastKnownLocation$6((Location) obj);
            }
        }).addOnFailureListener(new C0669v());
    }

    private com.google.android.gms.location.i getDistanceCalCallback() {
        com.google.android.gms.location.i iVar = new com.google.android.gms.location.i() {
            public void onLocationResult(LocationResult locationResult) {
                if (androidx.core.content.a.checkSelfPermission(LocationUpdateService.this.getApplicationContext(), "android.permission.ACCESS_FINE_LOCATION") != 0) {
                    androidx.core.content.a.checkSelfPermission(LocationUpdateService.this.getApplicationContext(), "android.permission.ACCESS_COARSE_LOCATION");
                }
            }
        };
        this.calDistanceCallback = iVar;
        return iVar;
    }

    private JSONObject getLatLng(Double d, Double d2) throws JSONException {
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("lat", d);
        jSONObject.put("lon", d2);
        return jSONObject;
    }

    private com.google.android.gms.location.i getLocationCallback() {
        com.google.android.gms.location.i iVar = new com.google.android.gms.location.i() {
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Location e0 = locationResult.e0();
                if (e0 == null) {
                    FirebaseCrashlytics.getInstance().recordException(new Exception("Null Location in getLocationCallback for ID : " + LocationUpdateService.this.driverId));
                    return;
                }
                LocationUpdateService.this.updated = true;
                android.util.Log.e(LocationUpdateService.LOG_TAG, "GoogleClient - CURRENT LOCATION FETCHED BY GPS");
                double latitude = e0.getLatitude();
                double longitude = e0.getLongitude();
                e0.getAccuracy();
                LocationUpdateService locationUpdateService = LocationUpdateService.this;
                locationUpdateService.lastLatitudeValue = latitude;
                locationUpdateService.lastLongitudeValue = longitude;
                long time = e0.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", new Locale("en", "US"));
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                String format = simpleDateFormat.format(new Date(time));
                LocationUpdateService.this.context.getSharedPreferences(LocationUpdateService.this.context.getString(R.string.preference_file_key), 0);
                LocationUpdateService locationUpdateService2 = LocationUpdateService.this;
                locationUpdateService2.updateStorage("LAST_KNOWN_LAT", String.valueOf(locationUpdateService2.lastLatitudeValue));
                LocationUpdateService locationUpdateService3 = LocationUpdateService.this;
                locationUpdateService3.updateStorage("LAST_KNOWN_LON", String.valueOf(locationUpdateService3.lastLongitudeValue));
                LocationUpdateService.this.callDriverCurrentLocationAPI(e0, format, "fused_location_callback", LocationSource.LastLocation.toString(), TriggerFunction.GoogleCallback.toString());
                LocationUpdateService.this.checkNearByPickupZone(e0);
                LocationUpdateService locationUpdateService4 = LocationUpdateService.this;
                locationUpdateService4.prevLat = locationUpdateService4.lastLatitudeValue;
                locationUpdateService4.prevLon = locationUpdateService4.lastLongitudeValue;
            }
        };
        this.locationCallback = iVar;
        return iVar;
    }

    private int getLocationPriority() {
        int locationPriority = Utils.getLocationPriority(DRIVER_CURRENT_LOCATION_PRIORITY_KEY);
        if (!this.driverRideStatus.equals("ON_PICKUP")) {
            locationPriority = Utils.getLocationPriority(DRIVER_FUSED_LOCATION_PRIORITY_KEY);
        }
        StringBuilder sb2 = new StringBuilder();
        sb2.append("Location Priority is ");
        sb2.append(locationPriority);
        sb2.append(" for driver app and ride status ");
        sb2.append(this.driverRideStatus);
        return locationPriority;
    }

    private JSONObject getLocationUpdatePoints(double d, double d2, SharedPreferences sharedPreferences, String str) {
        char c;
        try {
            JSONObject jSONObject = new JSONObject();
            String string = sharedPreferences.getString("MAKE_NULL_API_CALL", "NO");
            String string2 = sharedPreferences.getString("DEMO_MODE_PASSWORD", "null");
            if (sharedPreferences.getString("IS_DEMOMODE_ENABLED", "null").equals("true")) {
                switch (string2.hashCode()) {
                    case -2128891636:
                        if (string2.equals("1789234")) {
                            c = 3;
                            break;
                        }
                        c = 65535;
                        break;
                    case -1069522502:
                        if (string2.equals("7891234")) {
                            c = 0;
                            break;
                        }
                        c = 65535;
                        break;
                    case -1069519523:
                        if (string2.equals("7891567")) {
                            c = 6;
                            break;
                        }
                        c = 65535;
                        break;
                    case -1069518530:
                        if (string2.equals("7891678")) {
                            c = 7;
                            break;
                        }
                        c = 65535;
                        break;
                    case -1069517538:
                        if (string2.equals("7891788")) {
                            c = 5;
                            break;
                        }
                        c = 65535;
                        break;
                    case -1069517537:
                        if (string2.equals("7891789")) {
                            c = 4;
                            break;
                        }
                        c = 65535;
                        break;
                    case -160599092:
                        if (string2.equals("8917234")) {
                            c = 1;
                            break;
                        }
                        c = 65535;
                        break;
                    case 503442298:
                        if (string2.equals("9178234")) {
                            c = 2;
                            break;
                        }
                        c = 65535;
                        break;
                    default:
                        c = 65535;
                        break;
                }
                switch (c) {
                    case 0:
                        jSONObject.put("lat", 13.311895563147432d);
                        jSONObject.put("lon", 76.93981481869986d);
                        break;
                    case 1:
                        jSONObject.put("lat", 13.260559676317829d);
                        jSONObject.put("lon", 76.4785809882692d);
                        break;
                    case 2:
                        jSONObject.put("lat", 13.160550263780683d);
                        jSONObject.put("lon", 76.66727044721313d);
                        break;
                    case 3:
                        jSONObject.put("lat", 12.522069908884921d);
                        jSONObject.put("lon", 76.89518072273476d);
                        break;
                    case 4:
                        jSONObject.put("lat", 23.06194031948526d);
                        jSONObject.put("lon", 88.7637073215878d);
                        break;
                    case 5:
                        jSONObject.put("lat", 24.338294091147212d);
                        jSONObject.put("lon", 88.1949706368274d);
                        break;
                    case 6:
                        jSONObject.put("lat", 9.869715234892222d);
                        jSONObject.put("lon", 76.37632251438302d);
                        break;
                    case 7:
                        jSONObject.put("lat", 9.955097514840311d);
                        jSONObject.put("lon", 76.37173322025349d);
                        break;
                    default:
                        jSONObject.put("lat", d);
                        jSONObject.put("lon", d2);
                        updateStorage(LAST_LOCATION_TIME, str);
                        break;
                }
            } else {
                if (d != 0.0d && d2 != 0.0d) {
                    jSONObject.put("lat", d);
                    jSONObject.put("lon", d2);
                    updateStorage(LAST_LOCATION_TIME, str);
                }
                if (string.equals("NO")) {
                    return null;
                }
                jSONObject.put("lat", (Object) null);
                jSONObject.put("lon", (Object) null);
            }
            return jSONObject;
        } catch (Exception unused) {
            return null;
        }
    }

    private void getRoute(Double d, Double d2, Double d3, Double d4) {
        StringBuilder sb2 = new StringBuilder();
        String valueFromStorage = getValueFromStorage("REGISTERATION_TOKEN");
        String valueFromStorage2 = getValueFromStorage("BASE_URL");
        String valueFromStorage3 = getValueFromStorage("VERSION_NAME");
        if (valueFromStorage == null || valueFromStorage2 == null || valueFromStorage3 == null) {
            return;
        }
        try {
            String valueFromStorage4 = getValueFromStorage("RIDE_ID");
            if (valueFromStorage4 == null) {
                return;
            }
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(valueFromStorage2 + "/" + valueFromStorage4 + "/route").openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("token", valueFromStorage);
            httpURLConnection.setRequestProperty("x-client-version", valueFromStorage3);
            httpURLConnection.connect();
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                while (true) {
                    String readLine = bufferedReader.readLine();
                    if (readLine == null) {
                        this.rideWaypoints = String.valueOf((JSONArray) new JSONObject(String.valueOf(sb2)).get("points"));
                        return;
                    }
                    sb2.append(readLine);
                }
            } else {
                if (responseCode != 404) {
                    FirebaseAnalytics.getInstance(this.context).c("LS_ERROR_GETTING_ROUTE", new Bundle());
                    return;
                }
                HttpURLConnection httpURLConnection2 = (HttpURLConnection) new URL(valueFromStorage2 + "/trip/route").openConnection();
                httpURLConnection2.setRequestMethod("POST");
                httpURLConnection2.setRequestProperty("Content-Type", "application/json");
                httpURLConnection2.setRequestProperty("token", valueFromStorage);
                httpURLConnection2.setRequestProperty("x-client-version", valueFromStorage3);
                JSONObject jSONObject = new JSONObject();
                JSONObject latLng = getLatLng(d, d2);
                JSONObject latLng2 = getLatLng(d3, d4);
                JSONArray jSONArray = new JSONArray();
                jSONArray.put(latLng);
                jSONArray.put(latLng2);
                jSONObject.put("waypoints", jSONArray);
                jSONObject.put("mode", "CAR");
                jSONObject.put("calcPoints", true);
                httpURLConnection2.getOutputStream().write(jSONObject.toString().getBytes());
                httpURLConnection2.connect();
                if (httpURLConnection2.getResponseCode() != 200) {
                    FirebaseAnalytics.getInstance(this.context).c("LS_ERROR_GETTING_ROUTE", new Bundle());
                    return;
                }
                BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(httpURLConnection2.getInputStream()));
                while (true) {
                    String readLine2 = bufferedReader2.readLine();
                    if (readLine2 == null) {
                        this.rideWaypoints = String.valueOf((JSONArray) ((JSONObject) new JSONArray(String.valueOf(sb2)).get(0)).get("points"));
                        return;
                    }
                    sb2.append(readLine2);
                }
            }
        } catch (Exception e) {
            android.util.Log.e("get route api exception", e.toString());
        }
    }

    private SimpleDateFormat getUTCDateFormatter() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", new Locale("en", "US"));
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return simpleDateFormat;
    }

    private String getValueFromStorage(String str) {
        return KeyValueStore.read(getApplicationContext(), getApplicationContext().getString(R.string.preference_file_key), str, null);
    }

    private void initialiseJSONObjects() {
        metaDataForLocation = new JSONArray();
        deviceManufacturer = new JSONObject();
        deviceModel = new JSONObject();
        batteryPercentage = new JSONObject();
        isOnCharge = new JSONObject();
        triggerFunction = new JSONObject();
        androidVersion = new JSONObject();
    }

    private boolean isLocationEnabled() {
        LocationManager locationManager = (LocationManager) this.context.getSystemService("location");
        return locationManager != null && androidx.core.location.b.a(locationManager);
    }

    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService("connectivity");
        NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public void lambda$callDriverCurrentLocationAPI$1(String str) {
        try {
            if (str == null || str.trim().isEmpty()) {
                str = "{}";
            }
            JSONObject jSONObject = new JSONObject(str);
            if (jSONObject.has("errorCode")) {
                StringBuilder sb2 = new StringBuilder();
                sb2.append("API RESP - ");
                sb2.append(jSONObject);
                sb2.append(jSONObject.has("errorCode"));
                sb2.append(" -- ");
                sb2.append(jSONObject.get("errorCode"));
                sb2.append(" -- ");
                sb2.append(jSONObject.get("errorCode").equals("INVALID_TOKEN"));
            }
            if (jSONObject.has("errorCode") && (jSONObject.get("errorCode").equals("INVALID_TOKEN") || jSONObject.get("errorCode").equals("TOKEN_EXPIRED"))) {
                StringBuilder sb3 = new StringBuilder();
                sb3.append("Invalid token while updating location API ");
                sb3.append(jSONObject.get("errorCode"));
                updateStorage("REGISTERATION_TOKEN", "__failed");
                cancelTimer();
                onDestroy();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        this.executorLocUpdate.shutdown();
    }

    public void lambda$callDriverCurrentLocationAPI$2(SharedPreferences sharedPreferences, String str, MobilityCallAPI mobilityCallAPI, JSONArray jSONArray, double d, double d2, Handler handler) {
        final String str2;
        String str3;
        Map<String, String> baseHeaders = MobilityCallAPI.getBaseHeaders(this.context);
        String string = sharedPreferences.getString("BASE_URL", "null");
        String str4 = string + "/driver/location";
        if (!baseHeaders.containsKey("token") || Objects.equals(baseHeaders.get("token"), "__failed")) {
            str2 = null;
        } else {
            baseHeaders.put("source", str);
            String valueFromStorage = getValueFromStorage("MERCHANT_ID");
            String valueFromStorage2 = getValueFromStorage("VEHICLE_VARIANT");
            String valueFromStorage3 = getValueFromStorage(Utils.DRIVER_STATUS);
            if (valueFromStorage != null && valueFromStorage2 != null && valueFromStorage3 != null) {
                baseHeaders.put("mId", valueFromStorage);
                baseHeaders.put("vt", valueFromStorage2);
                baseHeaders.put("dm", valueFromStorage3.toUpperCase());
            } else if (this.vVariant == null || this.drMode == null || (str3 = this.merchantID) == null) {
                try {
                    JSONObject jSONObject = new JSONObject(mobilityCallAPI.callAPI(string + "/driver/profile", baseHeaders, "{}", "GET").getResponseBody());
                    if (jSONObject.has("mode")) {
                        String upperCase = jSONObject.get("mode").toString().toUpperCase();
                        this.drMode = upperCase;
                        baseHeaders.put("dm", upperCase);
                    }
                    JSONObject optJSONObject = jSONObject.optJSONObject("organization");
                    if (optJSONObject != null && optJSONObject.has("id")) {
                        String string2 = optJSONObject.getString("id");
                        this.merchantID = string2;
                        baseHeaders.put("mId", string2);
                        updateStorage("MERCHANT_ID", this.merchantID);
                    }
                    JSONObject optJSONObject2 = jSONObject.optJSONObject("linkedVehicle");
                    if (optJSONObject2 != null && optJSONObject2.has("variant")) {
                        String string3 = optJSONObject2.getString("variant");
                        this.vVariant = string3;
                        baseHeaders.put("vt", string3);
                        updateStorage("VEHICLE_VARIANT", this.vVariant);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Bundle bundle = new Bundle();
                    bundle.putString("error", e.toString());
                    FirebaseAnalytics.getInstance(this.context).c("LS_ERROR_GETTING_PROFILE", bundle);
                }
            } else {
                baseHeaders.put("mId", str3);
                baseHeaders.put("vt", this.vVariant);
                baseHeaders.put("dm", this.drMode);
            }
            StringBuilder sb2 = new StringBuilder();
            sb2.append("LocationPayload Size - ");
            sb2.append(jSONArray.length());
            MobilityAPIResponse callAPI = mobilityCallAPI.callAPI(str4, baseHeaders, jSONArray.toString());
            StringBuilder sb3 = new StringBuilder();
            sb3.append("DriverUpdateLoc API  RespCode - ");
            sb3.append(callAPI.getStatusCode());
            sb3.append(" RespBody - ");
            sb3.append(callAPI.getResponseBody());
            int statusCode = callAPI.getStatusCode();
            int i = 0;
            if ((statusCode >= 200 && statusCode < 300) || statusCode == 302) {
                StringBuilder sb4 = new StringBuilder();
                sb4.append("in 200 ");
                sb4.append(callAPI.getResponseBody());
                System.out.println("LOCATION_UPDATE: SUCCESS API respReader :- " + callAPI.getResponseBody());
                updateStorage(LOCATION_PAYLOAD, new JSONArray().toString());
                while (true) {
                    ArrayList<UpdateTimeCallback> arrayList = updateTimeCallbacks;
                    if (i >= arrayList.size()) {
                        break;
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", new Locale("en", "US"));
                    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                    String format = simpleDateFormat.format(new Date());
                    updateStorage("DRIVER_LOCATION_TS", format);
                    arrayList.get(i).triggerUpdateTimeCallBack(format, String.valueOf(d), String.valueOf(d2), "SUCCESS");
                    i++;
                }
            } else {
                if (statusCode >= 400 && statusCode < 500) {
                    updateStorage(LOCATION_PAYLOAD, new JSONArray().toString());
                }
                System.out.println("LOCATION_UPDATE: ERROR API respReader :- " + callAPI.getResponseBody());
                try {
                    String optString = new JSONObject(callAPI.getResponseBody()).optString("errorCode", "");
                    if (statusCode == 403 && optString.equals("DRIVER_BLOCKED")) {
                        while (true) {
                            ArrayList<UpdateTimeCallback> arrayList2 = updateTimeCallbacks;
                            if (i >= arrayList2.size()) {
                                break;
                            }
                            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", new Locale("en", "US"));
                            simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                            arrayList2.get(i).triggerUpdateTimeCallBack(simpleDateFormat2.format(new Date()), String.valueOf(d), String.valueOf(d2), optString);
                            i++;
                        }
                    }
                } catch (Exception e2) {
                    StringBuilder sb5 = new StringBuilder();
                    sb5.append("exception in decoding errorPayload ");
                    sb5.append(e2.getMessage());
                }
                StringBuilder sb6 = new StringBuilder();
                sb6.append("in error ");
                sb6.append(callAPI.getResponseBody());
                FirebaseCrashlytics.getInstance().recordException(new Exception("API Error in callDriverCurrentLocationAPI for ID : " + this.driverId + " $ Resp Code : " + statusCode + " $ Error : " + callAPI.getResponseBody()));
            }
            str2 = callAPI.getResponseBody();
        }
        handler.post(new Runnable() {
            @Override
            public final void run() {
                LocationUpdateService.this.lambda$callDriverCurrentLocationAPI$1(str2);
            }
        });
    }

    public void lambda$fetchCurrentLocationWithFallback$3(Location location) {
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat uTCDateFormatter = getUTCDateFormatter();
        if (location == null) {
            processLocation(null, uTCDateFormatter.format(new Date()), "timer_task_null_location");
            return;
        }
        long time = location.getTime();
        long j = this.remoteConfigs.getLong("location_time_expiry");
        if (j == 0) {
            j = 45000;
        }
        if (currentTimeMillis - time > j) {
            fetchFreshLocationWithHighAccuracy(uTCDateFormatter);
        } else {
            processLocation(location, uTCDateFormatter.format(new Date(time)), "timer_task");
        }
    }

    public static void lambda$fetchCurrentLocationWithFallback$4(Exception exc) {
        FirebaseCrashlytics.getInstance().recordException(exc);
        android.util.Log.e(LOG_TAG, "fetchCurrentLocationWithFallback Failure: " + exc.getMessage());
    }

    public void lambda$fetchFreshLocationWithHighAccuracy$5(SimpleDateFormat simpleDateFormat, Location location) {
        if (location != null) {
            processLocation(location, simpleDateFormat.format(new Date(location.getTime())), "fallback_high_accuracy");
        } else {
            System.out.println("FALLBACK_LOCATION: Still null");
            processLocation(null, simpleDateFormat.format(new Date()), "fallback_null_location");
        }
    }

    public void lambda$fetchLastKnownLocation$6(Location location) {
        if (location != null) {
            updateStorage("LAST_KNOWN_LAT", String.valueOf(location.getLatitude()));
            updateStorage("LAST_KNOWN_LON", String.valueOf(location.getLongitude()));
            callDriverCurrentLocationAPI(location, getUTCDateFormatter().format(new Date(location.getTime())), "COMING FROM TIMER", LocationSource.LastLocation.toString(), TriggerFunction.TimerTask.toString());
            checkNearByPickupZone(location);
            return;
        }
        FirebaseCrashlytics.getInstance().recordException(new Exception("Null Location in fusedLocationProviderClient$getLastLocation for ID : " + this.driverId));
    }

    public void lambda$updateDriverStatus$0(Boolean bool, ExecutorService executorService) {
        Context context = this.context;
        try {
            MobilityCallAPI.getInstance(this.context).callAPI(context.getSharedPreferences(context.getString(R.string.preference_file_key), 0).getString("BASE_URL", "null") + "/driver/setActivity?active=" + bool + "&mode=" + (bool.booleanValue() ? "ONLINE" : "OFFLINE"), MobilityCallAPI.getBaseHeaders(this.context));
            if (!bool.booleanValue()) {
                updateStorage("DRIVER_STATUS", "__failed");
                showAlertNotification();
                cancelTimer();
                androidx.work.D.h(this.context).a(this.context.getString(R.string.location_update));
                onDestroy();
            }
            executorService.shutdown();
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in updateDriverStatus " + e));
            StringBuilder sb2 = new StringBuilder();
            sb2.append("Catch in updateDriverStatus : ");
            sb2.append(e);
        }
    }

    private void logEventForHealthCheck(Intent intent) {
        if (intent != null) {
            String stringExtra = intent.getStringExtra("StartingSource");
            if (stringExtra != null && stringExtra.equals(MyFirebaseMessagingService.NotificationTypes.TRIGGER_SERVICE)) {
                FirebaseAnalytics.getInstance(this).c("service_triggered_by_health_check", new Bundle());
            } else {
                if (stringExtra == null || !stringExtra.equals("TRIGGER_SERVICE_INACTIVE")) {
                    return;
                }
                FirebaseAnalytics.getInstance(this).c("service_by_health_check_inactive", new Bundle());
            }
        }
    }

    private void processLocation(Location location, String str, String str2) {
        if (location != null) {
            updateStorage("LAST_KNOWN_LAT", String.valueOf(location.getLatitude()));
            updateStorage("LAST_KNOWN_LON", String.valueOf(location.getLongitude()));
            callDriverCurrentLocationAPI(location, str, str2, LocationSource.CurrentLocation.toString(), TriggerFunction.TimerTask.toString());
            checkNearByPickupZone(location);
            return;
        }
        callDriverCurrentLocationAPI(null, str, str2, LocationSource.CurrentLocation.toString(), TriggerFunction.TimerTask.toString());
        FirebaseCrashlytics.getInstance().recordException(new Exception("Null Location even after fallback for ID: " + this.driverId));
    }

    public static void registerCallback(UpdateTimeCallback updateTimeCallback) {
        updateTimeCallbacks.add(updateTimeCallback);
    }

    private void resetTimer(int i, float f, int i2) {
        com.google.android.gms.location.i iVar;
        cancelTimer();
        com.google.android.gms.location.e eVar = this.fusedLocationProviderClient;
        if (eVar != null && (iVar = this.locationCallback) != null) {
            eVar.removeLocationUpdates(iVar);
        }
        startLocationUpdates(i, f, i2);
    }

    private void showAlertNotification() {
        System.out.println("Notification");
        Context context = this.context;
        String string = context.getSharedPreferences(context.getString(R.string.preference_file_key), 0).getString("REGISTERATION_TOKEN", "null");
        if (string.equals("null") || string.equals("__failed")) {
            return;
        }
        PendingIntent activity = PendingIntent.getActivity(this, 1868818, getPackageManager().getLaunchIntentForPackage(this.context.getPackageName()), 67108864);
        m.e eVar = new m.e(this.context, "General");
        eVar.p(BitmapFactory.decodeResource(getResources(), Utils.getResIdentifier(this.context, "ic_launcher", "drawable")));
        eVar.l(getString(R.string.we_made_you_offline)).x(Utils.getResIdentifier(this.context, Build.VERSION.SDK_INT >= 26 ? "ic_launcher_small_icon" : "ny_ic_launcher", "drawable")).k(getString(R.string.location_is_turned_off_permission_is_disabled)).e(true).u(2);
        eVar.j(activity);
        androidx.core.app.p b = androidx.core.app.p.b(this.context);
        if (androidx.core.content.a.checkSelfPermission(this, "android.permission.POST_NOTIFICATIONS") != 0) {
            android.util.Log.e(LOG_TAG, "no notification permission");
        } else {
            b.d(1868818, eVar.b());
            startGPSListeningService();
        }
    }

    private void showWidget(boolean z) {
        try {
            Context context = this.context;
            String string = context.getSharedPreferences(context.getString(R.string.preference_file_key), 0).getString("ACTIVITY_STATUS", "null");
            Intent intent = new Intent(getApplicationContext(), (Class<?>) WidgetService.class);
            if (string.equals("onPause") || string.equals("onDestroy")) {
                if (z) {
                    intent.putExtra("showNearbySpecialPickup", true);
                    intent.putExtra("specialPickupMessage", getString(R.string.you_are_near_a_special_pickup_zone));
                } else {
                    intent.putExtra("showNearbySpecialPickup", false);
                }
                startService(intent);
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in ShowWidget " + e));
            e.printStackTrace();
        }
    }

    private void startGPSListeningService() {
        try {
            Intent intent = new Intent(this, (Class<?>) GpsListeningService.class);
            SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), 0);
            intent.addFlags(268468224);
            int i = Build.VERSION.SDK_INT;
            if (i >= 31 && sharedPreferences.getString("ACTIVITY_STATUS", "null").equals("onPause")) {
                ((AlarmManager) this.context.getSystemService("alarm")).setExact(0, System.currentTimeMillis(), PendingIntent.getBroadcast(this.context, 0, new Intent(this.context, (Class<?>) GPSBroadcastReceiver.class), 67108864));
            } else if (i >= 26) {
                getApplicationContext().startForegroundService(intent);
            } else {
                startService(intent);
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in startGPSLIsteningService " + e));
            FirebaseAnalytics.getInstance(this).c("Exception_in_startGPSListeningService", (Bundle) null);
            android.util.Log.e(LOG_TAG, "Error in startGPSListeningService : " + e);
        }
    }

    private void startLocationUpdates(int i, float f, int i2) {
        if (isLocationUpdating.booleanValue()) {
            return;
        }
        this.delayForG = i;
        this.minDispDistance = f;
        this.delayForT = i2;
        isLocationUpdating = Boolean.TRUE;
        checkLocation();
        this.fusedLocationProviderClient.requestLocationUpdates(createLocationRequest(this.delayForGNew, this.minDispDistanceNew), getLocationCallback(), Looper.getMainLooper());
        TimerTask createTimer = createTimer();
        if (this.timer == null) {
            this.timer = new Timer();
        }
        this.timer.scheduleAtFixedRate(createTimer, 0L, this.delayForT);
    }

    private void updateConfigVariables() {
        try {
            SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), 0);
            this.maximumLimit = Integer.parseInt(sharedPreferences.getString("MAX_LIMIT_TO_STORE_LOCATION_PT", "60"));
            this.driverRideStatus = sharedPreferences.getString("DRIVER_RIDE_STATUS", "ON_PICKUP");
            this.maximumLimitNotOnRide = Integer.parseInt(sharedPreferences.getString("MAX_LIMIT_TO_STORE_LOCATION_PT_NOT", "1"));
            String string = sharedPreferences.getString("RIDE_G_FREQUENCY", null);
            this.delayForGNew = string != null ? Integer.parseInt(string) : 50000;
            String string2 = sharedPreferences.getString("RIDE_T_FREQUENCY", null);
            this.delayForTNew = string2 != null ? Integer.parseInt(string2) : 20000;
            String string3 = sharedPreferences.getString("DRIVER_MIN_DISPLACEMENT", null);
            this.minDispDistanceNew = string3 != null ? Float.parseFloat(string3) : 30.0f;
            String string4 = sharedPreferences.getString("GPS_METHOD", null);
            if (string4 == null) {
                string4 = "CURRENT";
            }
            this.gpsMethodSwitch = string4;
            this.cancellationTokenSource = new CancellationTokenSource();
        } catch (Exception e) {
            android.util.Log.e(LOG_TAG, "Exception updateConfigVariables " + e);
        }
    }

    private void updateDeviceDetails() {
        try {
            updateJSONObject(deviceManufacturer, "deviceManufacturer", Build.MANUFACTURER);
            updateJSONObject(androidVersion, "androidVersion", Build.VERSION.SDK_INT);
            updateJSONObject(deviceModel, "deviceModel", Build.MODEL);
            metaDataForLocation.put(deviceManufacturer);
            metaDataForLocation.put(deviceModel);
            metaDataForLocation.put(androidVersion);
        } catch (JSONException e) {
            e.printStackTrace();
            StringBuilder sb2 = new StringBuilder();
            sb2.append("Unable to put data in metaData ");
            sb2.append(e);
        }
    }

    private void updateDriverStatus(final Boolean bool) {
        final ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
        newSingleThreadExecutor.execute(new Runnable() {
            @Override
            public final void run() {
                LocationUpdateService.this.lambda$updateDriverStatus$0(bool, newSingleThreadExecutor);
            }
        });
    }

    private void updateJSONObject(JSONObject jSONObject, String str, String str2) throws JSONException {
        JSONObject jSONObject2 = new JSONObject();
        jSONObject2.put("key", str);
        jSONObject2.put("value", str2);
    }

    private JSONArray updateLocationPayload(SharedPreferences sharedPreferences) {
        String string = sharedPreferences.getString(LOCATION_PAYLOAD, null);
        if (string == null) {
            return new JSONArray();
        }
        try {
            JSONArray jSONArray = new JSONArray(string);
            String valueFromStorage = getValueFromStorage("IS_RIDE_ACTIVE");
            if (valueFromStorage != null && valueFromStorage.equals("false")) {
                return new JSONArray();
            }
            while (jSONArray.length() > 1 && jSONArray.length() >= this.maximumLimit) {
                jSONArray.remove(0);
                if (this.pointsToRemove > 1000000) {
                    this.pointsToRemove = 1;
                }
            }
            return jSONArray;
        } catch (JSONException e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in buffered locations " + e));
            e.printStackTrace();
            StringBuilder sb2 = new StringBuilder();
            sb2.append("Unable to parse buffered Locations from sharedPref");
            sb2.append(e);
            return new JSONArray();
        }
    }

    private void updateMetaData(String str) {
        try {
            BatteryManager batteryManager = (BatteryManager) this.context.getSystemService("batterymanager");
            int intProperty = batteryManager.getIntProperty(4);
            boolean isCharging = batteryManager.isCharging();
            updateJSONObject(batteryPercentage, "batteryPercentage", intProperty);
            updateJSONObject(isOnCharge, "isOnCharge", isCharging);
            updateJSONObject(triggerFunction, "triggerFunction", str);
        } catch (JSONException e) {
            e.printStackTrace();
            StringBuilder sb2 = new StringBuilder();
            sb2.append("Json exception while putting data in metaData");
            sb2.append(e);
        }
    }

    public void updateStorage(String str, String str2) {
        Context context = this.context;
        SharedPreferences.Editor edit = context.getSharedPreferences(context.getString(R.string.preference_file_key), 0).edit();
        edit.putString(str, str2);
        edit.apply();
    }

    public void appendLatLngToFile(String str) {
        File filesDir = getFilesDir();
        File file = new File(filesDir + "/lat_long.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filesDir, "lat_long.txt"), true);
            fileOutputStream.write((str + "\n").getBytes());
            fileOutputStream.close();
            PrintStream printStream = System.out;
            printStream.println("NammaMeter: Writen to file " + file);
            printStream.println("NammaMeter: value " + str);
        } catch (Exception e) {
            System.out.println("Exception e " + e.toString());
        }
    }

    public boolean canCallAPI(boolean z) {
        long currentTimeMillis = System.currentTimeMillis();
        long j = currentTimeMillis - this.lastCallTime;
        if (j >= 2050 && z) {
            this.lastCallTime = currentTimeMillis;
            return true;
        }
        FirebaseCrashlytics.getInstance().recordException(new Exception("canCallAPI false for ID : " + this.driverId + " $ ExecutorStatus : " + z + " $ timeSinceLastCall : " + j));
        return false;
    }

    public void checkVersionMismatch() {
        String valueFromStorage = getValueFromStorage("LOCATION_SERVICE_VERSION");
        if (valueFromStorage == null || valueFromStorage.equals("V1")) {
            return;
        }
        stopSelf();
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("NammaMeter: onBind");
        this.storeLocationInFile = false;
        return this.binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.context = getApplicationContext();
        try {
            if (Build.VERSION.SDK_INT >= 29) {
                startForeground(15082022, createNotification(), 8);
            } else {
                startForeground(15082022, createNotification());
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in onCreate onCreate LocationUpdateService " + e));
            android.util.Log.e(LOG_TAG, "Error in onCreate -> ", e);
        }
        this.remoteConfigs = new MobilityRemoteConfigs(false, false);
        updateConfigVariables();
        initialiseJSONObjects();
        isLocationUpdating = Boolean.FALSE;
        this.fusedLocationProviderClient = com.google.android.gms.location.k.a(this);
        ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
        this.executorLocUpdate = newSingleThreadExecutor;
        newSingleThreadExecutor.shutdown();
        this.timer = new Timer();
        resetTimer(this.delayForGNew, this.minDispDistanceNew, this.delayForTNew);
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                android.util.Log.i("LOCATION_UPDATE_SERVICE", "internet broadcast receiver received a callback");
                if (LocationUpdateService.this.isNetworkAvailable(context) && !MobilityCommonBridge.isServiceRunning(context, GRPCNotificationService.class.getName()) && MobilityCommonBridge.isServiceRunning(context, LocationUpdateService.class.getName())) {
                    android.util.Log.i("LOCATION_UPDATE_SERVICE", "internet broadcast receiver received a callback with network available state");
                    context.startService(new Intent(context, (Class<?>) GRPCNotificationService.class));
                }
            }
        };
        this.internetBroadcastReceiver = broadcastReceiver;
        try {
            this.context.unregisterReceiver(broadcastReceiver);
        } catch (Exception e2) {
            android.util.Log.i("LOCATION_UPDATE_SERVICE", "Error faced in removing the internet broadcast receiver : " + e2);
        }
        if (Build.VERSION.SDK_INT >= 33) {
            com.facebook.react.devsupport.i.a(this.context, this.internetBroadcastReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"), 2);
        } else {
            this.context.registerReceiver(this.internetBroadcastReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
        }
    }

    @Override
    public void onDestroy() {
        com.google.android.gms.location.i iVar;
        super.onDestroy();
        isLocationUpdating = Boolean.FALSE;
        cancelTimer();
        com.google.android.gms.location.e eVar = this.fusedLocationProviderClient;
        if (eVar != null && (iVar = this.locationCallback) != null) {
            eVar.removeLocationUpdates(iVar);
        }
        ExecutorService executorService = this.executorLocUpdate;
        if (executorService != null) {
            executorService.shutdown();
        }
        stopForeground(true);
        try {
            android.util.Log.i("SERVICE", " I am here to stop GRPC service ");
            if (MobilityCommonBridge.isServiceRunning(this.context, GRPCNotificationService.class.getName())) {
                this.context.stopService(new Intent(this.context, (Class<?>) GRPCNotificationService.class));
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in onCreate StopGRPSService " + e));
            android.util.Log.i("SERVICE", "Error in stopping the GRPC service from OnDestroy of location update service " + e);
        }
        stopSelf();
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        System.out.println("NammaMater: onRebind");
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        try {
            if (Build.VERSION.SDK_INT >= 29) {
                startForeground(15082022, createNotification(), 8);
            } else {
                startForeground(15082022, createNotification());
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in onStartCommand NotificationService " + e));
            android.util.Log.e(LOG_TAG, "Error in onStartCommand -> ", e);
        }
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), 0);
        if (sharedPreferences != null) {
            this.driverId = sharedPreferences.getString("DRIVER_ID", "null");
        }
        if (intent != null) {
            String stringExtra = intent.hasExtra("TRIP_STATUS") ? intent.getStringExtra("TRIP_STATUS") : null;
            if (!isDistanceCalulation.booleanValue() && stringExtra != null && stringExtra.equals("started")) {
                updateStorage("TRIP_DISTANCE_ACC", "0");
                updateStorage("TRIP_DISTANCE", "0");
                finalDistanceWithAcc = 0;
                finalDistance = 0;
            } else if (stringExtra != null && stringExtra.equals("ended")) {
                StringBuilder sb2 = new StringBuilder();
                sb2.append("OnStart - StopDistanceCalculation with values - FinalDistance: ");
                sb2.append(finalDistance);
                sb2.append(", FinalAccDistance: ");
                sb2.append(finalDistanceWithAcc);
                sb2.append(" LFinalDistance - ");
                sb2.append(getValueFromStorage("TRIP_DISTANCE"));
                sb2.append(" LFinalAccDistance - ");
                sb2.append(getValueFromStorage("TRIP_DISTANCE_ACC"));
                finalDistanceWithAcc = 0;
                finalDistance = 0;
                isDistanceCalulation = Boolean.FALSE;
            }
        }
        initialiseJSONObjects();
        updateDeviceDetails();
        updateConfigVariables();
        logEventForHealthCheck(intent);
        int i3 = this.delayForGNew;
        if (i3 != this.delayForG || this.minDispDistanceNew != this.minDispDistance || this.delayForTNew != this.delayForT) {
            resetTimer(i3, this.minDispDistanceNew, this.delayForTNew);
        } else if (!isLocationUpdating.booleanValue()) {
            startLocationUpdates(this.delayForGNew, this.minDispDistanceNew, this.delayForTNew);
        }
        try {
            if (MobilityCommonBridge.isServiceRunning(this.context, GRPCNotificationService.class.getName())) {
                return 1;
            }
            android.util.Log.i("SERVICE", " Starting GRPC service from onStartCommand location update service ");
            this.context.startService(new Intent(this.context, (Class<?>) GRPCNotificationService.class));
            return 1;
        } catch (Exception e2) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in onCreate Start GRPC Service " + e2));
            android.util.Log.i("SERVICE", "Error in starting the GRPC service from onStartCommand of location update service " + e2);
            return 1;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("NammaMeter: onUnbind");
        this.storeLocationInFile = true;
        super.onUnbind(intent);
        return true;
    }

    private void updateJSONObject(JSONObject jSONObject, String str, int i) throws JSONException {
        JSONObject jSONObject2 = new JSONObject();
        jSONObject2.put("key", str);
        jSONObject2.put("value", i);
    }

    private void updateJSONObject(JSONObject jSONObject, String str, boolean z) throws JSONException {
        JSONObject jSONObject2 = new JSONObject();
        jSONObject2.put("key", str);
        jSONObject2.put("value", z);
    }
}