package histogram;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import java.awt.datatransfer.*;

import GUI.FileChooser;
import GUI.internalFrame;
import GUI.mainWindow;
import ij.*;
import ij.process.*;
import ij.measure.*;
import ij.plugin.filter.Analyzer;
import ij.plugin.filter.Filler;
import ij.plugin.filter.PlugInFilter;
import ij.text.TextWindow;
import ij.gui.*;

public class VerticalHistogram {
	
	ImagePlus imp;
	ImageProcessor ip, nip;
	public static internalFrame[] intFrameHorizHistogram;
	private int number;
	public int[][] hist;
	int numberResult;
	
	public VerticalHistogram(ImagePlus imp, ImageProcessor ip,  int number, int numberResult){
		this.imp = imp;
		this.ip = ip;
		this.number = number;
		this.numberResult = numberResult;
		
        ImageStack stack = imp.getStack();
        int slices = imp.getStackSize();
        ip = stack.getProcessor(slices);	
		
		drawHistogram();
		getMinimas();
	}
	
	public void drawHistogram(){
		
		ImagePlus imp2 = NewImage.createImage ("Threshold", ip.getWidth(), ip.getHeight(), 5, 8, NewImage.FILL_WHITE);
		nip = imp2.getProcessor();		
		setHistogram();
		mainWindow.intFrameArrayList.add(new internalFrame("Vertical Projection Profile" , FileChooser.number, imp2, ip.getWidth(), ip.getHeight(), hist, numberResult, 0));
		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 void setHistogram(){

		hist = new int[1][ip.getWidth()];
		Arrays.fill(hist[0], 0);
		for (int i = 0; i < ip.getWidth(); i++) {
			for (int j = 0; j < ip.getHeight(); j++) {
				if (ip.getPixelValue(i, j) == 0) {
					hist[0][i] = hist[0][i] + 1;
					nip.putPixelValue(i, ip.getHeight() - hist[0][i], 0);
				}
			}
		}
	}
	
	public void getMinimas(){
		int[] sort = new int[hist.length];
		for (int i = 0; i < sort.length; i++) {
			sort[i] = hist[0][i];
		}
		Arrays.sort(sort);
		
		for (int i = 0; i < hist[0].length; i++) {
			System.out.println("hist "+hist[0][i]);
		}
		for (int i = 0; i < sort.length; i++) {
			System.out.println("sort "+sort[i]);
		}
		
		ArrayList minimums = new ArrayList();
		for (int i = 0; i < hist.length / 2; i++) {
			if (hist[0][i] <= sort[sort.length /2])
				minimums.add(i);
		}
		for (int i = 0; i < minimums.size(); i++) {
			System.out.println("min "+minimums.get(i));
		}
	}

}
