

package com.ejada.hmg.geofence.intent_receivers

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.ejada.hmg.geofence.GeofenceTransition
import com.ejada.hmg.geofence.HMG_Geofence
import com.ejada.hmg.utils.Logs
import com.google.android.gms.location.GeofenceStatusCodes
import com.google.android.gms.location.GeofencingEvent

class GeofenceBroadcastReceiver : BroadcastReceiver() {
  private val LOG_TAG = "GeofenceBroadcastReceiver"
  override fun onReceive(context: Context, intent: Intent) {

    val geofencingEvent = GeofencingEvent.fromIntent(intent)
    if (geofencingEvent.hasError()) {
      val errorMessage = GeofenceErrorMessages.getErrorString(context, geofencingEvent.errorCode)
      Log.e(LOG_TAG, errorMessage)
      
      Logs.GeofenceEvent.save(context,LOG_TAG,"Error while triggering geofence event",Logs.STATUS.ERROR)
      doReRegisterIfRequired(context,geofencingEvent.errorCode)

      return
    }

    Logs.GeofenceEvent.save(context,LOG_TAG,"Geofence event triggered: ${GeofenceTransition.fromInt(geofencingEvent.geofenceTransition).value} for ${geofencingEvent.triggeringGeofences.map {it.requestId}}",Logs.STATUS.SUCCESS)
    HMG_Geofence.shared(context).handleEvent(geofencingEvent.triggeringGeofences,geofencingEvent.triggeringLocation, GeofenceTransition.fromInt(geofencingEvent.geofenceTransition));
    
  }

  fun doReRegisterIfRequired(context: Context, errorCode: Int){
    val errorRequiredReregister = listOf(
            GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE,
            GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES,
            GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS,
            GeofenceStatusCodes.GEOFENCE_REQUEST_TOO_FREQUENT
    )

    if(errorRequiredReregister.contains(errorCode))
      HMG_Geofence.shared(context).register(){ status, error ->

      }

  }
}