package org.kne.cloud.network.srv6;

import java.util.Arrays;

public class SingleDijkstraAlgorithm implements DijkstraAlgorithm {

	private long[][] heap;
	private long[][]pointers;
	
	private long[] direction;
	private long[] shortest;
	private boolean[] flags;
	private long startPoint;
	

	@Override
	public void setGraph(long[][] pointers,long[][] heap,long startPoint) {
		this.heap=heap;
		this.pointers=pointers;
		/*for (int i = 0; i < pointers.length; i++) {
			for (int j = 0; j < pointers[i].length; j++) {
				System.out.println("pointers["+i+"]["+j+"]="+pointers[i][j]);
			}
		}
		for (int i = 0; i < heap.length; i++) {
			for (int j = 0; j < heap[i].length; j++) {
				System.out.println("heap["+i+"]["+j+"]="+heap[i][j]);
			}
		}*/

		this.startPoint=startPoint;
	}

	@Override
	public void run() {
		direction=new long[pointers.length];
		shortest=new long[pointers.length];
		flags=new boolean[pointers.length];
		Arrays.fill(shortest, MAX_WEIGHT);
		Arrays.fill(direction, -1);
		
		
		shortest[(int) startPoint]=0;
		direction[(int) startPoint]=startPoint;
		
		for(long i=1;i<pointers.length;i++) {
			long shortestNode=-1;
			long shortestLength=MAX_WEIGHT+1;
			for(long j=0;j<pointers.length;j++) {
				if(flags[(int) j]) {
					continue;
				}
				long pathLength=shortest[(int) j];
				if(pathLength<shortestLength) {
					shortestLength=pathLength;
					shortestNode=j;
				}
			}
			flags[(int) shortestNode]=true;
			
			
			long pointer =pointers[(int) shortestNode][0];
			long count =pointers[(int) shortestNode][1];
			for (long j = 0; j < count; j++) {
				long lenthJ=heap[(int) (pointer+j)][1]+shortestLength;
				long pos= heap[(int) (pointer+j)][0];
				if(lenthJ<shortest[(int)pos]) {
					shortest[(int)pos]=lenthJ;
					direction[(int)pos]=shortestNode;
				}
			}
		}
	}

	@Override
	public long[] getDirection() {
		return direction;
	}

	@Override
	public long[] getShortest() {
		return shortest;
	}

}
