class GeofenceHelper(context: Context) {

    fun buildGeofencingRequest(geofences: List<Geofence>): GeofencingRequest {
        return GeofencingRequest.Builder()
            .setInitialTrigger(0)
            .addGeofences(geofences)
            .build()
    }

    val geofencePendingIntent: PendingIntent by lazy {
        val intent = Intent(context, GeofenceBroadcastReceiver::class.java)
        PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
    }

    fun setupParentGeofence(
        context: Context,
        userLat: Double,
        userLong: Double,
        geofencingClient: GeofencingClient
    ) {

        //Create Parent geofence model with id "p0" and radius 300km
        val parentGeoFence = GeofenceModel("p0", userLat, userLong, 300000.0)

        //Build parent Geofence
        val geofence = buildGeoFence(parentGeoFence, GeoFenceType.PARENT)
      
        //Check Background Location permission is granted
        if (geofence != null && ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_BACKGROUND_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
          
            geofencingClient
                .addGeofences(
                  buildGeofencingRequest(listOf(geofence)),
                  geofencePendingIntent)
                .addOnSuccessListener {
                    "Parent Geofence Added Successfully".log("GEO","Parent Geofence Success")
                }
                .addOnFailureListener {
                    "Parent Geofence Add Failed".log("GEO", "Parent Geofence Failed")
                }
        }
    }
    
    
    fun buildGeoFence(geofence: GeofenceModel, type: GeoFenceType): Geofence? {
        
        val latitude = geofence.lat
        val longitude = geofence.lng
        val radius = geofence.radius

        if (latitude != null && longitude != null && radius != null) {

            val builder = Geofence.Builder()
                .setRequestId(geofence.id)
                .setCircularRegion(
                    latitude,
                    longitude,
                    radius.toFloat()
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)

            //Set Exit Transition for parent region
            if (type == GeoFenceType.PARENT) {
                builder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
                
            //Set Enter Transition for child region
            } else {
                builder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
            }

            return builder.build()
        }
        return null
    }

}

enum class GeoFenceType {
    PARENT, CHILD
}