package com.teltonikaServer.bl;

public class SpeedStatistic {

    private int maxSpeed = 0;
    private int points = 0;
    private int speedSum = 0;
    private Integer lastSpeed = null;
    private Long lastTimestamp = null;
    private long accumSpeedTime = 0;
    private long accumTime = 0;

    public SpeedStatistic(int baseSpeed, long timestamp) {
        this.addSpeed(baseSpeed, timestamp);
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getAvgSpeed() {
        return speedSum / points;
    }

    public int getPonderatedAvgSpeed() {
        
        int pondAvg;
        
        try{
            pondAvg = (this.points > 1)?(int) (accumSpeedTime / accumTime):getAvgSpeed();
        } catch(Exception e){
            pondAvg = getAvgSpeed();
        }
        return pondAvg;
    }

    public int getPoints() {
        return points;
    }

    public void setPoints(int points) {
        this.points = points;
    }

    public void addSpeed(int speed, long timestamp) {
        this.maxSpeed = Math.max(speed, this.maxSpeed);
        this.speedSum += speed;

        if (lastSpeed != null && lastTimestamp != null) {
            this.accumSpeedTime += ((lastSpeed+speed)/2)*(timestamp - lastTimestamp);
            accumTime += (timestamp - lastTimestamp);
        }
        
        this.points++;
        lastSpeed = speed;
        lastTimestamp = timestamp;
    }
}
