package com.algobase.service;

import com.algobase.stracks.sTracksRoot;

import android.location.Location;


public class LocationBuffer {

  static final float DISTANCE_UNDEFINED = sTracksRoot.DISTANCE_UNDEFINED;

  Location buf[];

  int sz;
  int count;

  int first;
  int last;

  int alt_len;
  int spd_len;

  double max_dist;

  float gps_alt_avg;
  float gps_spd_avg;

  double tdist;


 private Location loc(int i) { return buf[i % sz]; }

 public LocationBuffer() 
 { 
   sz = 32;
   buf = new Location[sz];

   alt_len = 8;
   spd_len = 4;
   max_dist = 100;

   first = 0;
   last = -1;
   count = 0;
   gps_alt_avg = DISTANCE_UNDEFINED;
   gps_spd_avg = 0;
   tdist = 0;
  }

 public void clear() {
   first = 0;
   last = -1;
   count = 0;
   gps_alt_avg = DISTANCE_UNDEFINED;
   gps_spd_avg = 0;
   tdist = 0;
 }


 public int length() { return last - first + 1; }

 public double total_dist() { return tdist; }

 public float getCurrentAltitude()   { return gps_alt_avg; }
 public float getCurrentSpeed()   { return gps_spd_avg; }


 public void add(Location loc) 
 { 
   buf[count++ % sz] = loc;

   double alt_sum = 0;
   int alt_l = alt_len;
   if (alt_l > count) alt_l = count;

   for(int i=0; i<alt_l;i++)
   { int j = (count-i-1) % sz;
     //if (loc.distanceTo(buf[j]) > max_dist) break;
     alt_sum  += buf[j].getAltitude();
    }

   gps_alt_avg = (float)(alt_sum/alt_l);


   double spd_sum = 0;
   int spd_l = spd_len;
   if (spd_l > count) spd_l = count;

   for(int i=0; i<spd_l;i++)
   { int j = (count-i-1) % sz;
     //if (loc.distanceTo(buf[j]) > max_dist) break;
     spd_sum  += buf[j].getSpeed();
    }

   gps_spd_avg = (float)(spd_sum/spd_l);
 }



 public void add_old(Location loc) 
 { 
   last++;

   buf[last % sz] = loc;

   tdist = 0;

   int i = last-1;
   while(i >= first && tdist < max_dist) 
   { tdist += loc(i).distanceTo(loc(i+1)); 
     i--;
    }

   if (i > first) first = i;

   if (length() > alt_len) first++;

   double alt_sum = 0;
   double spd_sum = 0;

   for(int j = first; j<=last; j++) 
   { alt_sum  += loc(j).getAltitude();
     spd_sum  += loc(j).getSpeed();
    }

   gps_alt_avg = (float)(alt_sum/length());
   gps_spd_avg = (float)(spd_sum/length());
  }

}

