package representation;

import java.util.ArrayList;

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

import GUI.FileChooser;
import GUI.internalFrame;
import GUI.mainWindow;
	
public class Dilatation {
		
	ImagePlus imp, imp2;
	ImageProcessor ip, nip;
	int numberResult;
	boolean draw;
		
	public Dilatation(ImagePlus imp, ImageProcessor ip, int numberResult, boolean draw) {
		this.imp = imp;
		this.ip = ip;
		this.numberResult = numberResult;
		this.draw = draw;
	}	

	public void run(){
		
		imp2 = NewImage.createImage ("Threshold", ip.getWidth(), ip.getHeight(), 1, 8, NewImage.FILL_WHITE);
		nip = imp2.getProcessor();
		ArrayList white_i, white_j;
		white_i = new ArrayList();
		white_j = new ArrayList();
		
		for (int i = 0; i < ip.getWidth(); i++) {
			for (int j = 0; j < ip.getHeight(); j++) {
				if (ip.getPixelValue(i, j) == 0) {
					nip.putPixelValue(i, j, 0);
					nip.putPixelValue(i, j, 0);
					nip.putPixelValue(i, j-1, 0);
					nip.putPixelValue(i-1, j-1, 0);
					nip.putPixelValue(i-1, j, 0);
					nip.putPixelValue(i-1, j+1, 0);
					white_i.add(i);
					white_j.add(j+1);
					white_i.add(i+1);
					white_j.add(j-1);
					white_i.add(i+1);
					white_j.add(j);
					white_i.add(i+1);
					white_j.add(j+1);					
				}
			}
		}

		for (int i = 0; i < white_i.size(); i++) 
			nip.putPixelValue(Integer.parseInt(white_i.get(i).toString()), Integer.parseInt(white_j.get(i).toString()), 0);
		
		
		if (draw) {
			mainWindow.intFrameArrayList.add(new internalFrame("Dilatation", 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;
		}
		
	}
	
	public ImagePlus getImg(){
		return imp2;
	}
	
	public ImageProcessor getIp(){
		return nip;
	}	
	
	
	protected void finalize() throws Throwable {
	    try {
	        //close();        // close open files
	    } finally {
	        super.finalize();
	        System.out.println("dilatation has been finalized.");
	    }
	}	

}


