package cl.smartcities.isci.transportinspector.onBusService.filters;

import android.location.Location;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;

import cl.smartcities.isci.transportinspector.onBusService.ActivityLocation;

/**
 * Created by Agustin on 31/10/2017.
 */

public class InstantVelocityFilter {

    private static final String TAG = InstantVelocityFilter.class.getSimpleName();

    private final int maxVelocity;

    public InstantVelocityFilter(int maxVelocity) {
        this.maxVelocity = maxVelocity;
    }

    public List<ActivityLocation> filter(List<ActivityLocation> inputLocations) {
        if (inputLocations.size()<2) return inputLocations;

        ListIterator<ActivityLocation> iterator = inputLocations.listIterator();
        Location l1 = iterator.next();
        while (iterator.hasNext()) {
            Location l2 = iterator.next();

            float distanceInMeters = l1.distanceTo(l2);
            long timeInMillis = Math.abs(l1.getTime() - l2.getTime());

            float deltaV = distanceInMeters * 3600 / timeInMillis;

            if (deltaV > maxVelocity) {
                Log.d(TAG, String.format(Locale.getDefault(),
                        "dV exceeded %f | P1: %f,%f | P2: %f,%f", deltaV,
                        l1.getLatitude(), l1.getLongitude(), l2.getLatitude(), l2.getLongitude()));
                return new ArrayList<>();
            }
            l1 = l2;
        }
        return inputLocations;
    }
}
