package pl.edu.pw.mini.jk.sg.game.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class SimpleAccidentHistory implements AccidentHistory {
	private final List<Accident> accidents;
	private final int timeHorizon;
	private int currentTimestep;

	
	
	@Override
	public void registerAccident(Accident accident) {
		int index = Collections.binarySearch(accidents, accident,
				(a1, a2) -> a1.timeStep() - a2.timeStep());
		if (index < 0)
			index = -index - 1;
		accidents.add(index, accident);
	}

	@Override
	public void setCurrentTimestep(int timeStep) {
		accidents.removeIf(a -> a.timeStep() <= timeStep - timeHorizon);
		this.currentTimestep = timeStep;
	}

	public SimpleAccidentHistory(int timeHorizon) {
		super();
		this.timeHorizon = timeHorizon;
		currentTimestep = 0;
		accidents = new ArrayList<Accident>();
	}
	

	private SimpleAccidentHistory(List<Accident> accidents, int timeHorizon, int currentTimestep) {
        super();
        this.accidents = accidents;
        this.timeHorizon = timeHorizon;
        this.currentTimestep = currentTimestep;
    }

    @Override
	public Collection<Accident> getAccidents(int timeHorizon) {
		return accidents.stream()
				.filter(a -> a.timeStep() > currentTimestep - timeHorizon)
				.collect(Collectors.toList());
	}
	
	@Override
	public SimpleAccidentHistory typedClone()  {
	        return new SimpleAccidentHistory(new ArrayList<>(accidents), timeHorizon, currentTimestep);
	}
}
