package com.jifalops.wsnlocalize.signal;

import com.jifalops.wsnlocalize.data.DistanceEstimator;

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

/**
 *
 */
public class BestDistanceEstimator {
    public interface OnReadyListener {
        void onReady();
    }

    final List<DistanceEstimator>
            bt = new ArrayList<>(),
            btle = new ArrayList<>(),
            wifi = new ArrayList<>(),
            wifi5g = new ArrayList<>();

    final EstimatorHelper helper;

    public BestDistanceEstimator(final OnReadyListener callback) {
        helper = new EstimatorHelper(new EstimatorHelper.EstimatorsCallback() {
            @Override
            public void onEstimatorsLoaded() {
                for (DistanceEstimator e : helper.getBt()) {
                    if (e.results.error < DistanceEstimator.GOOD_ERROR) bt.add(e);
                }
                for (DistanceEstimator e : helper.getBtle()) {
                    if (e.results.error < DistanceEstimator.GOOD_ERROR) btle.add(e);
                }
                for (DistanceEstimator e : helper.getWifi()) {
                    if (e.results.error < DistanceEstimator.GOOD_ERROR) wifi.add(e);
                }
                for (DistanceEstimator e : helper.getWifi5g()) {
                    if (e.results.error < DistanceEstimator.GOOD_ERROR) wifi5g.add(e);
                }
                callback.onReady();
            }
        });
    }

    public int getBtSize() { return bt.size(); }
    public int getBtleSize() { return btle.size(); }
    public int getWifiSize() { return wifi.size(); }
    public int getWifi5gSize() { return wifi5g.size(); }

    public double estimateBt(double[] sample) {
        return estimate(bt, sample);
    }
    public double estimateBtle(double[] sample) {
        return estimate(btle, sample);
    }
    public double estimateWifi(double[] sample) {
        return estimate(wifi, sample);
    }
    public double estimateWifi5g(double[] sample) {
        return estimate(wifi5g, sample);
    }

    private double estimate(List<DistanceEstimator> list, double[] sample) {
        if (list.size() == 0) return 0;
        double estimate = 0;
        for (DistanceEstimator e : list) {
            estimate += e.estimate(sample);
        }
        return estimate / list.size();
    }
}

@@ -90,16 +90,68 @@
 timator;
+%0Aimport com.jifalops.wsnlocalize.toolbox.util.Stats;
 %0A%0Aimport
@@ -2165,19 +2165,25 @@
        i
-f (
+nt len = 
 list.siz
@@ -2185,16 +2185,33 @@
 t.size()
+;%0A        if (len
  == 0) r
@@ -2229,24 +2229,26 @@
       double
+%5B%5D
  estimate = 
@@ -2248,53 +2248,65 @@
 mate
+s
  = 
-0;%0A        for (DistanceEstimator e : list
+new double%5Blen%5D;%0A        for (int i = 0; i %3C len; ++i
 ) %7B%0A
@@ -2329,13 +2329,26 @@
 mate
- += e
+s%5Bi%5D = list.get(i)
 .est
@@ -2391,29 +2391,30 @@
 urn 
-estimate / list.size(
+Stats.median(estimates
 );%0A 

changed to median