package de.hems.trafficsim;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

public class Track extends Observable {
    protected List<Vehicle> vehicles;
    protected List<List<VehicleTimeRecord>> vtrList;
    protected float trackLength;
    protected float sumAvgMemory;
    protected float sumDelAvgMemory;
    protected int historyLength;
    protected float overallAvg;
    protected float delayedAvg;
    protected float lastAvg;
    protected int waitTime;
    protected float maxVelocity;
    protected float brakeProb;
    protected long steps;
    protected Semaphore listSemaphore;

    public List<List<VehicleTimeRecord>> getVtrList() { return vtrList; }
    public float getOverallAvg() {
        return overallAvg;
    }
    public float getLastAvg() {
        return lastAvg;
    }
    public float getDelayedAvg() { return delayedAvg; }
    public List<Vehicle> getVehicles() {
        return vehicles;
    }
    public float getTrackLength() {
        return trackLength;
    }
    public long getSteps() { return steps; }
    public Semaphore getListSemaphore() { return listSemaphore; }
    public int getHistoryLength() { return historyLength; }

    public Track(int numberVehicles, float trackLength, float brakeProb, float maxVelocity, int waitTime, int historyLength) {
        this.trackLength = trackLength;
        this.brakeProb = brakeProb;
        this.maxVelocity = maxVelocity;
        this.vehicles = createVehiclesList(numberVehicles);
        this.vtrList = new LinkedList<>();
        this.sumAvgMemory = 0;
        this.sumDelAvgMemory = 0;
        this.overallAvg = 0;
        this.delayedAvg = 0;
        this.lastAvg = 0;
        this.historyLength = historyLength;
        this.waitTime = waitTime;
        this.steps = 0;
        this.listSemaphore = new Semaphore(1);

    }

    protected List<Vehicle> createVehiclesList(int numberVehicles){
        List<Vehicle> result = new ArrayList<>();
        for(int i=0;i<numberVehicles;i++){
            Vehicle vehicle = new Vehicle(i, i, this.maxVelocity, this.brakeProb, this.trackLength);
            result.add(vehicle);
        }

        return result;
    }

    public void setWaitTime(int waitTime) {
        this.waitTime = waitTime;
    }

    public void setBrakeProb(float brakeProb) {
        for (Vehicle v : this.vehicles) {
            v.setBrakeProb(brakeProb);
        }
    }

    public void setMaxVelocity(float maxVelocity) {
        for (Vehicle v : this.vehicles) {
            v.setMaxVelocity(maxVelocity);
        }
    }

    public void timeElapse() {
        for(int i=0; i<vehicles.size();i++) {
            Vehicle v = vehicles.get(i);
            int forerunnerIndex = i + 1;
            if (forerunnerIndex >= vehicles.size()) {
                forerunnerIndex -= vehicles.size();
            }
            Vehicle forerunner = vehicles.get(forerunnerIndex);
            float distanceForerunner = forerunner.getPosition() - v.getPosition() - 1;
            if(distanceForerunner < 0.0){
                distanceForerunner += this.trackLength;
            }
            v.updateVelocity(distanceForerunner);
        }

        try {
            this.listSemaphore.acquire();
        } catch (InterruptedException ex) {return;}
        List <VehicleTimeRecord> records = new ArrayList<>(vehicles.size());
        this.vtrList.add(records);
        if (this.vtrList.size() > this.historyLength) {
            this.vtrList.remove(0);
        }
        for(Vehicle v: vehicles){
            v.timeElapse();
            VehicleTimeRecord vtr = new VehicleTimeRecord(v.id, v.position, v.curVelocity, v.maxVelocity);
            records.add(vtr);
        }
        steps++;
        this.listSemaphore.release();

        update_avg();
        this.setChanged();
        //this.notifyObservers();
        this.clearChanged();
        //LockSupport.parkNanos(1);
        try  {
            Thread.sleep(waitTime);
        } catch (InterruptedException ex) { }
    }

    public float avg_step(int step){
        float sum_step = 0;
        for (VehicleTimeRecord r : vtrList.get(step)) {
            sum_step +=  r.velocity;
        }
        return sum_step / vehicles.size();
    }

    protected void update_avg(){
        lastAvg = avg_step(vtrList.size()-1);
        if (this.steps > 10) {
            sumDelAvgMemory += lastAvg;
            delayedAvg = sumDelAvgMemory / (this.steps - 10);
        }
        sumAvgMemory += lastAvg;
        overallAvg = sumAvgMemory / this.steps;

    }

    public float avg_span(int start, int end){
        float sum_span = 0;
        for (int i=start; i <end;i++){
            sum_span += avg_step(i);
        }
        return sum_span / (end-start+1);
    }

}
