package de.hft.geotracker

import android.content.BroadcastReceiver
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Intent
import android.util.Log
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofenceStatusCodes
import com.google.android.gms.location.GeofencingEvent

class GeofenceBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        val geofencingEvent = GeofencingEvent.fromIntent(intent)
        if (geofencingEvent.hasError()) {
            val errorMessage = GeofenceStatusCodes.getStatusCodeString(geofencingEvent.errorCode)
            println("Event error")
            Log.e(TAG, errorMessage)
            return
        }

        // Test that the reported transition was of interest.
        when (val geofenceTransition = geofencingEvent.geofenceTransition) {
            Geofence.GEOFENCE_TRANSITION_ENTER -> {
                context!!.getSharedPreferences("LOCATION", Context.MODE_PRIVATE)
                    ?.edit()
                    ?.putBoolean("ENABLED", true)
                    ?.apply()

                // Get the geofences that were triggered. A single event can trigger multiple geofences.
                val triggeringGeofences = geofencingEvent.triggeringGeofences
                // Get the transition details as a String.
                val geofenceTransitionDetails = "Transition: $geofenceTransition" +
                        "\nTriggering Geofences: $triggeringGeofences"
                println("Success Transition: ")
                Log.i(TAG, geofenceTransitionDetails)
            }
            Geofence.GEOFENCE_TRANSITION_EXIT -> {
                context!!.getSharedPreferences("LOCATION", Context.MODE_PRIVATE)
                    ?.edit()
                    ?.putBoolean("ENABLED", false)
                    ?.apply()

                val triggeringGeofences = geofencingEvent.triggeringGeofences
                val geofenceTransitionDetails =
                    "Transition: $geofenceTransition\nTriggering Geofences: $triggeringGeofences"
                println("Success Transition: ")
                Log.i(TAG, geofenceTransitionDetails)
            }
            else -> {
                println("Error Transition: ")
                Log.e(TAG, geofenceTransition.toString())
            }
        }
    }

}