package com.project.ilsaenterprise.services;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;

import com.google.android.gms.location.LocationResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

public class NewTrackerBroadcast extends BroadcastReceiver {
    public static final String ACTION = "com.typroject.perkebunan_nusantara.UPDATE_LOCATION";

    DatabaseReference silentTrackRef;
    FirebaseAuth mAuth;
    String currentUser;
    String currentDate = new SimpleDateFormat("dd MMMM yyyy", Locale.getDefault()).format(new Date());
    private ArrayList<Integer> listVal;
    HashMap<String, String> profileMap;

    public NewTrackerBroadcast(){
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser().getUid();
        silentTrackRef = FirebaseDatabase.getInstance().getReference("NewTracker").child(currentUser);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        if(intent != null){
            final String action = intent.getAction();
            if(action.equals(ACTION)){
                LocationResult result = LocationResult.extractResult(intent);
                if(result != null){
                    Location location = result.getLastLocation();
                    if(!currentUser.equals("")){
                        silentTrackRef.child(currentDate).child(ts).setValue(location);
                    }
                    else
                    {
                        //silentTrackRef.child(currentUser).setValue(location);
                        return;
                    }
                }
            }
            else
                return;
        }
        else
            return;

    }
}