package com.urbanairship.location;

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.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import com.urbanairship.LocationOptions;
import com.urbanairship.Logger;
import com.urbanairship.UAirship;
import com.urbanairship.analytics.LocationEvent;
import com.urbanairship.location.ILocationService;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
public class LocationService extends Service {
    public static final String ACTION_START = "com.urbanairship.location.START";
    public static final String ACTION_STOP = "com.urbanairship.location.STOP";
    public static final String LOCATION_CHANGED = "com.urbanairship.location.LOCATION_CHANGED";
    public static final String REQUESTED_ACCURACY_KEY = "com.urbanairship.location.REQUESTED_ACCURACY";
    public static final String SINGLE_LOCATION_CHANGED = "com.urbanairship.location.SINGLE_LOCATION_CHANGED";
    private String bestProvider;
    private Context context;
    private Criteria criteria;
    private String currentProvider;
    private ProviderListener gpsListener;
    private LastLocationFinder lastLocationFinder;
    private Location location;
    private PendingIntent locationChangedPendingIntent;
    private LocationManager locationManager;
    private ProviderListener networkListener;
    private PendingIntent singleLocationChangedPendingIntent;
    private static boolean started = false;
    private static boolean bound = false;
    private final ILocationService.Stub locationBinder = new ILocationService.Stub() { // from class: com.urbanairship.location.LocationService.2
        @Override // com.urbanairship.location.ILocationService
        public void createLocationEvent(Location location, int i, int i2) {
            LocationService.this.location = location;
            UAirship.shared().getAnalytics().addEvent(new LocationEvent(LocationService.this.location, LocationEvent.UpdateType.SINGLE, i, i2));
        }

        @Override // com.urbanairship.location.ILocationService
        public String getBestProvider() {
            return LocationService.this.bestProvider;
        }

        @Override // com.urbanairship.location.ILocationService
        public Criteria getCriteria() {
            return LocationService.this.criteria;
        }

        @Override // com.urbanairship.location.ILocationService
        public String getCurrentProvider() {
            return LocationService.this.currentProvider;
        }

        @Override // com.urbanairship.location.ILocationService
        public Location getLocation() {
            return LocationService.this.location;
        }

        @Override // com.urbanairship.location.ILocationService
        public void requestSingleLocationUpdate(Criteria criteria) {
            Logger.info("Requesting a single update.");
            if (criteria == null && (LocationService.this.currentProvider == null || "".equals(LocationService.this.currentProvider))) {
                LocationService.this.initializeCriteria();
                LocationService.this.setProviders();
            }
            int accuracy = criteria == null ? LocationService.this.criteria.getAccuracy() : criteria.getAccuracy();
            String bestProvider = criteria == null ? LocationService.this.currentProvider : LocationService.this.locationManager.getBestProvider(criteria, true);
            LocationService.this.createSingleLocationChangedPendingIntent(accuracy);
            LocationService.this.locationManager.requestLocationUpdates(bestProvider, 0L, 0.0f, LocationService.this.singleLocationChangedPendingIntent);
        }

        @Override // com.urbanairship.location.ILocationService
        public void resetProviders() {
            LocationService.this.setProviders();
            if (LocationService.started) {
                LocationService.this.initializeLocationUpdates();
            }
        }

        @Override // com.urbanairship.location.ILocationService
        public void setCriteria(Criteria criteria) {
            LocationService.this.criteria = criteria;
            LocationService.this.createLocationChangedPendingIntent();
        }
    };
    private BroadcastReceiver locationChangedReceiver = new BroadcastReceiver() { // from class: com.urbanairship.location.LocationService.3
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            Location location;
            int i;
            if ((LocationService.LOCATION_CHANGED.equals(intent.getAction()) || LocationService.SINGLE_LOCATION_CHANGED.equals(intent.getAction())) && (location = (Location) intent.getExtras().get("location")) != null) {
                Logger.info("Received a location update.");
                Logger.verbose("Location: " + location.toString());
                LocationEvent.UpdateType updateType = LocationEvent.UpdateType.CONTINUOUS;
                if (LocationService.SINGLE_LOCATION_CHANGED.equals(intent.getAction())) {
                    Logger.info("Received a single-shot location update.");
                    LocationService.this.locationManager.removeUpdates(LocationService.this.singleLocationChangedPendingIntent);
                    updateType = LocationEvent.UpdateType.SINGLE;
                    i = 0;
                } else {
                    i = UAirship.shared().getAirshipConfigOptions().locationOptions.updateIntervalMeters;
                }
                LocationService.this.location = location;
                UAirship.shared().getAnalytics().addEvent(new LocationEvent(location, updateType, intent.getIntExtra(LocationService.REQUESTED_ACCURACY_KEY, -1), i));
                Intent intent2 = new Intent(UALocationManager.ACTION_LOCATION_UPDATE);
                intent2.putExtra(UALocationManager.LOCATION_KEY, LocationService.this.location);
                context.sendBroadcast(intent2);
            }
        }
    };

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    public class ProviderListener implements LocationListener {
        private ProviderListener() {
        }

        @Override // android.location.LocationListener
        public void onLocationChanged(Location location) {
        }

        @Override // android.location.LocationListener
        public void onProviderDisabled(String str) {
            Logger.info("Location provider disabled: " + str);
            if (str.equals(LocationService.this.currentProvider)) {
                Logger.info("Current provider (" + str + ") disabled, resetting providers.");
                LocationService.this.setProviders();
                LocationService.this.initializeLocationUpdates();
            }
        }

        @Override // android.location.LocationListener
        public void onProviderEnabled(String str) {
            Logger.info("Location provider enabled: " + str);
            if ((str.equals(LocationService.this.currentProvider) || !str.equals(LocationService.this.bestProvider)) && LocationService.this.currentProvider != null) {
                return;
            }
            Logger.info("Best provider (" + str + ") now available; resetting providers.");
            LocationService.this.currentProvider = str;
            LocationService.this.initializeLocationUpdates();
        }

        @Override // android.location.LocationListener
        public void onStatusChanged(String str, int i, Bundle bundle) {
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void createLocationChangedPendingIntent() {
        Intent intent = new Intent(LOCATION_CHANGED);
        intent.putExtra(REQUESTED_ACCURACY_KEY, this.criteria.getAccuracy());
        this.locationChangedPendingIntent = PendingIntent.getBroadcast(this.context, 0, intent, 268435456);
    }

    private synchronized void createService() {
        bound = true;
        this.context = UAirship.shared().getApplicationContext();
        this.locationManager = (LocationManager) this.context.getSystemService("location");
        registerReceivers();
        initializeCriteria();
        createSingleLocationChangedPendingIntent(this.criteria.getAccuracy());
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void createSingleLocationChangedPendingIntent(int i) {
        Intent intent = new Intent(SINGLE_LOCATION_CHANGED);
        intent.putExtra(REQUESTED_ACCURACY_KEY, i);
        this.singleLocationChangedPendingIntent = PendingIntent.getBroadcast(this.context, 0, intent, 268435456);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void initializeCriteria() {
        LocationOptions locationOptions = UAirship.shared().getAirshipConfigOptions().locationOptions;
        this.criteria = new Criteria();
        this.criteria.setAccuracy(locationOptions.horizontalAccuracy);
        this.criteria.setPowerRequirement(locationOptions.powerRequirement);
        this.criteria.setCostAllowed(locationOptions.costAllowed);
        this.criteria.setAltitudeRequired(locationOptions.altitudeRequired);
        this.criteria.setSpeedRequired(locationOptions.speedRequired);
        this.criteria.setBearingRequired(locationOptions.bearingRequired);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void initializeLocationUpdates() {
        Logger.info("Removing location update requests with the old provider");
        this.locationManager.removeUpdates(this.locationChangedPendingIntent);
        if (this.currentProvider == null) {
            Logger.info("There are no available providers, waiting to request updates.");
            return;
        }
        LocationOptions locationOptions = UAirship.shared().getAirshipConfigOptions().locationOptions;
        Logger.info("Requesting location updates with the new provider: " + this.currentProvider);
        this.locationManager.requestLocationUpdates(this.currentProvider, locationOptions.updateIntervalMeters, (float) (locationOptions.updateIntervalSeconds * 1000), this.locationChangedPendingIntent);
    }

    private void initializeProviderListeners() {
        LocationOptions locationOptions = UAirship.shared().getAirshipConfigOptions().locationOptions;
        if (UAirship.shared().getAirshipConfigOptions().locationOptions.allowGPSForLocationTracking) {
            this.gpsListener = new ProviderListener();
            this.locationManager.requestLocationUpdates(this.bestProvider, locationOptions.updateIntervalMeters, (float) (locationOptions.updateIntervalSeconds * 1000), this.gpsListener);
        }
        this.networkListener = new ProviderListener();
        this.locationManager.requestLocationUpdates(LocationEvent.AllowableProvider.NETWORK.toString().toLowerCase(), locationOptions.updateIntervalMeters, (float) (locationOptions.updateIntervalSeconds * 1000), this.networkListener);
    }

    private void invokeLastLocationFinder() {
        Logger.debug("Invoking last location finder.");
        this.lastLocationFinder = new LastLocationFinder(this.context);
        new AsyncTask<Void, Void, Void>() { // from class: com.urbanairship.location.LocationService.1
            /* JADX INFO: Access modifiers changed from: protected */
            @Override // android.os.AsyncTask
            public Void doInBackground(Void... voidArr) {
                LocationOptions locationOptions = UAirship.shared().getAirshipConfigOptions().locationOptions;
                Location lastBestLocation = LocationService.this.lastLocationFinder.getLastBestLocation(locationOptions.updateIntervalMeters, locationOptions.updateIntervalSeconds * 1000);
                if (lastBestLocation == null) {
                    Logger.info("No last best location found.");
                    return null;
                }
                Logger.info(String.format("Last best location found at lat: %f, long: %f with provider: %s", Double.valueOf(lastBestLocation.getLatitude()), Double.valueOf(lastBestLocation.getLongitude()), lastBestLocation.getProvider()));
                Intent intent = new Intent(LocationService.LOCATION_CHANGED);
                intent.putExtra("location", lastBestLocation);
                LocationService.this.context.sendBroadcast(intent);
                return null;
            }
        }.execute(new Void[0]);
    }

    private void registerReceivers() {
        Logger.debug("Registering location change receivers.");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LOCATION_CHANGED);
        intentFilter.addAction(SINGLE_LOCATION_CHANGED);
        this.context.registerReceiver(this.locationChangedReceiver, intentFilter);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void setProviders() {
        if (UAirship.shared().getAirshipConfigOptions().locationOptions.allowGPSForLocationTracking) {
            this.bestProvider = this.locationManager.getBestProvider(this.criteria, false);
            if (this.locationManager.isProviderEnabled(this.bestProvider)) {
                this.currentProvider = this.bestProvider;
            } else {
                this.currentProvider = this.locationManager.getBestProvider(this.criteria, true);
            }
        } else {
            this.bestProvider = LocationEvent.AllowableProvider.NETWORK.toString().toLowerCase();
            this.currentProvider = this.locationManager.isProviderEnabled(this.bestProvider) ? this.bestProvider : null;
        }
        Logger.info(String.format("Current location provider: %s, best location provider: %s", this.currentProvider, this.bestProvider));
    }

    private synchronized void setupService() {
        if (started) {
            Logger.debug("Location service already started.");
        } else {
            started = true;
            setProviders();
            invokeLastLocationFinder();
            createLocationChangedPendingIntent();
            initializeProviderListeners();
            initializeLocationUpdates();
        }
    }

    private synchronized void teardownService() {
        this.locationManager.removeUpdates(this.networkListener);
        if (this.gpsListener != null) {
            this.locationManager.removeUpdates(this.gpsListener);
        }
        this.context.unregisterReceiver(this.locationChangedReceiver);
        if (started) {
            this.locationManager.removeUpdates(this.locationChangedPendingIntent);
        }
        started = false;
        bound = false;
        stopSelf();
    }

    @Override // android.app.Service
    public IBinder onBind(Intent intent) {
        return this.locationBinder;
    }

    @Override // android.app.Service
    public void onCreate() {
        if (!UAirship.shared().isFlying()) {
            Logger.error("LocationService started prior to a UAirship.takeOff() call.");
            throw new IllegalStateException("UAirship.takeOff() must be called every time Application.onCreate() is invoked.");
        }
        super.onCreate();
        if (bound) {
            return;
        }
        createService();
    }

    @Override // android.app.Service
    public void onDestroy() {
        Logger.info("Location service destroyed");
        teardownService();
    }

    @Override // android.app.Service
    public void onStart(Intent intent, int i) {
        Logger.debug("Location Service started with intent=" + intent);
        super.onStart(intent, i);
        if (intent == null || intent.getAction() == null) {
            Logger.warn("Attempted to start service with null intent or action.");
            return;
        }
        String action = intent.getAction();
        if (action.equals(ACTION_STOP)) {
            if (started) {
                teardownService();
            }
        } else if (!action.equals(ACTION_START)) {
            Logger.warn("Unknown action: " + intent.getAction());
        } else if (started) {
        } else {
            setupService();
        }
    }
}
