package com.noovudev.geofence.capacitorgeofenceboxtracker;

import android.app.IntentService;
import android.content.Intent;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

import java.util.ArrayList;
import java.util.List;

public class GeofenceIntentService extends IntentService {
    private static final String TAG = "Geofence Broadcast";

    public GeofenceIntentService() {
        super(TAG);
    }

    private String getGeofenceTransitionDetails(List<Geofence> triggeringGeofences) {

        ArrayList<String> triggeringGeofencesIdsList = new ArrayList<>();
        for (Geofence geofence : triggeringGeofences) {
            triggeringGeofencesIdsList.add(geofence.getRequestId());
        }
        String triggeringGeofencesIdsString = TextUtils.join(", ",  triggeringGeofencesIdsList);

        return triggeringGeofencesIdsString;
    }

    private String getTransitionString(int transitionType) {
        switch (transitionType) {
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                return "GEOFENCE_TRANSITION_ENTER";
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                return "GEOFENCE_TRANSITION_EXIT";
            default:
                return "UNKNOWN_GEOFENCE_TRANSITION";
        }
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {

            Log.e(TAG, geofencingEvent.getErrorCode() + "");
            return;
        }

        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            String geofenceTransitionDetails = getGeofenceTransitionDetails(triggeringGeofences);

            // Send notification and log the transition details.

            // GeofenceTracker.notifyTracker(geofenceTransitionDetails, geofenceTransition);
            intent.setAction("location");
            String echoMessage = "IntentService after a pause of 3 seconds echoes ";
            LocalBroadcastManager.getInstance(getApplicationContext())
                    .sendBroadcast(intent.putExtra("broadcastMessage", geofenceTransitionDetails+"//"+geofenceTransition));

            Log.i(TAG, geofenceTransitionDetails);
        } else {
            // Log the error.
            Log.e(TAG, "GEOFENCE_TRANSITION_INVALID_TYPE" + geofenceTransition);
        }
    }
}