package trafficjams.model.classes;
import trafficjams.model.interfaces.ICrossRoad;
import trafficjams.model.interfaces.IMapElement;
import trafficjams.model.interfaces.IRoad;
import java.util.ArrayList;
import java.util.ListIterator;
/**
* Created by IntelliJ IDEA.
* User: Администратор
* Date: 20.11.11
* Time: 23:06
* To change this template use File | Settings | File Templates.
*/
public class Trip {
private ArrayList<ICrossRoad> trip = null;
public Trip(ArrayList<ICrossRoad> trip){
this.trip = trip;
}
public IRoad getNextElement(IMapElement _currentElement, boolean fToL) throws Exception {
if(_currentElement.getClass().equals(IRoad.class)){
IRoad currentElement = (IRoad) _currentElement;
ICrossRoad first = currentElement.getFCross();
ICrossRoad last = currentElement.getLCross();
ICrossRoad nextCross = this.getNextCross(first,last);
if (nextCross !=null){
if (nextCross.equals(first)&&!fToL){
return currentElement;
}
if (nextCross.equals(last)&&fToL){
return currentElement;
}
if (fToL){
return this.findRoad(first, nextCross);
}
if (!fToL){
return this.findRoad(last,nextCross);
}
throw new Exception("paths errors!!") ;
}else {
return null;
}
}else {
ICrossRoad currentElement = (ICrossRoad) _currentElement;
ICrossRoad nextCross = this.getNextCross(currentElement);
if (nextCross !=null){
if(nextCross.equals(currentElement)){
return this.getNextElement(currentElement, fToL);
}
return this.findRoad(currentElement,nextCross);
}else {
return null;
}
//throw new Exception("paths errors!!") ;
}
}
private IRoad findRoad(ICrossRoad currentElement, ICrossRoad nextCross) throws Exception {
return ((CrossRoad)currentElement).findRoad(nextCross);
}
private ICrossRoad getNextCross(ICrossRoad currentElement) {
ListIterator<ICrossRoad> iter = trip.listIterator();
ICrossRoad nextCross = null;
while (iter.hasNext()){
//nextCross = iter.next();
if (iter.next().equals(currentElement)){
nextCross = null;
if (iter.hasNext()){
nextCross = iter.next();
}
iter.previous();
//trim trip
while (iter.hasPrevious()){
iter.previous();
iter.remove();
}
break;
}else {
nextCross = null;
}
}
return nextCross;
}
public ICrossRoad getNextCross(ICrossRoad first, ICrossRoad last) {
ListIterator<ICrossRoad> iter = trip.listIterator();
ICrossRoad nextCross = null;
//boolean isFinded = false;
while (iter.hasNext()){
nextCross = iter.next();
if (nextCross.equals(first)||nextCross.equals(last)){
nextCross = null;
if (iter.hasNext()){
nextCross = iter.next();
}
iter.previous();
//trim trip
while (iter.hasPrevious()){
iter.previous();
iter.remove();
}
break;
}else {
nextCross =null;
}
}
return nextCross;
}
}