package com.app.simplitend.patientgeofencing;

import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Build;

import androidx.annotation.NonNull;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.maps.model.LatLng;

public class GeoFenceHelper extends ContextWrapper {

    public static final String GEOFENCE_TAG = "PATIENT_GEOFENCE";
    private PendingIntent pendingIntent;

    public static final int BROADCAST_REQUEST_CODE = 10001;
    public static final String GEOFENCE_ACTION = "com.simplitend.ACTION_GEOFENCE";

    public static final String GEOFENCE_ID = "com.simplitent.PATIENT_GEOFENCE";

    public GeoFenceHelper(Context base) {
        super(base);
    }

    public GeofencingRequest getGeoFencingRequest(Geofence geofence){
        return new GeofencingRequest.Builder()
                .addGeofence(geofence)
                .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT)
                .build();
    }

    public Geofence getGeoFence(@NonNull String GEOFENCE_ID,
                                @NonNull LatLng latLng, float radius, int transitionType){
        return new Geofence.Builder()
                .setCircularRegion(latLng.latitude, latLng.longitude, radius)
                .setRequestId(GEOFENCE_ID)
                .setTransitionTypes(transitionType)
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setLoiteringDelay(5000) // This does nothing if the transition is not DWELL
                .build();
    }

    public synchronized PendingIntent getPendingIntent(){
        if (pendingIntent != null){
            return pendingIntent;
        }

        Intent intent = new Intent(this, GeoFenceBroadcastReceiver.class);
        intent.setAction(GEOFENCE_ACTION);

        if(Build.VERSION.SDK_INT > 30){
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
        } else{
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        return pendingIntent;
    }
}
