package representation;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;

import GUI.FileChooser;
import GUI.internalFrame;
import GUI.mainWindow;

import ij.ImagePlus;
import ij.gui.NewImage;
import ij.process.ImageProcessor;

public class VerticalRunLength {
	
	ImagePlus imp, imp2;
	ImageProcessor ip, nip;
	int numberResult;

	class verRunLength{
		int r; //the row of horizontal run
		int c1, c2; //first and last columns of the run
		int len; //lenght of the run
		int traced; //tracing indicator
		verRunLength righRun;
	}
	
	class HrunLink {
		verRunLength hptr;
		HrunLink next;
	}
	
	public VerticalRunLength(ImagePlus imp, ImageProcessor ip, int numberResult) {
		this.imp = imp;
		this.numberResult = numberResult;
		this.ip = ip;
		
		ArrayList list = new ArrayList();
		
		int i = 0;
		int j = 0;
		while (i<ip.getWidth()) {
			j = 0;
			while (j<ip.getHeight()){
				if (ip.getPixelValue(i, j) == 0) {
					if  ((i == 0) || ( (i != 0) && (ip.getPixelValue(i, j-1) == 255) )) {
						verRunLength hrl = new verRunLength();
						hrl.r = i;
					//	System.out.println("hrl.r "+hrl.r);
						hrl.c1 = j;
					//	System.out.println("hrl.c1 "+hrl.c1);
						while (ip.getPixelValue(i, j) == 0)
							j++;
						hrl.c2 = j-1;
					//	System.out.println("hrl.c2 "+hrl.c2);
						hrl.len = hrl.c2 - hrl.c1;
						//System.out.println("hrl.len "+hrl.len);
						list.add(hrl);
					}
						
				}
				j++;
			}
			i++;
		}
		
		
		ImagePlus imp2 = NewImage.createRGBImage ("Vertical Run Length", ip.getWidth(), ip.getHeight(), 1, NewImage.FILL_WHITE);
		ImageProcessor nip = imp2.getProcessor();
		
		Random random = new Random();
		Color randomColor = Color.getHSBColor( random.nextFloat(), 1.0F, 1.0F );

		for (i = 0; i < list.size(); i++) {
			verRunLength hrl = ((verRunLength)(list.get(i)));
			randomColor = Color.getHSBColor( random.nextFloat(), 1.0F, 1.0F );

			int color = ((randomColor.getRed() & 0xff) << 16) + ((randomColor.getGreen() & 0xff) << 8) + (randomColor.getBlue() & 0xff);

			for (int k = 0; k < hrl.len; k++) {
				nip.putPixel(hrl.r, hrl.c1 + k, color);
			}
		}
		
		mainWindow.intFrameArrayList.add(new internalFrame("Vertical Run Length", imp2, FileChooser.number, numberResult, 1, true));
		try {
			//mainWindow.intFrame[FileChooser.number].setSelected(true);
			((internalFrame)(mainWindow.intFrameArrayList.get(FileChooser.number))).setSelected(true);
		} catch(Exception e){
			System.out.println("Chyba");
		}	
		++FileChooser.number;
	}
	
}
