import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.frame.*;
import java.awt.event.*;
import java.io.*;

public class TintaSaturazioneValore1 extends PlugInFrame implements ActionListener, AdjustmentListener{
	Panel panel;
	
	Button buttonReset, buttonPreview, buttonApply;
	
	ImagePlus imp;
	ImageProcessor ip;
	
	Label tinta, saturazione, valore;
	TextField tTinta, tSaturazione, tValore;
	Scrollbar sTinta, sSaturazione, sValore;
	
	private int type;
	private long time;
	private int hue, saturation, value;
	public TintaSaturazioneValore1() {
		super("Tinta/Saturazione/Valore");
		
		imp = WindowManager.getCurrentImage();
		ip = imp.getProcessor();
		type = imp.getType();
		
		hue = 0;
		saturation = 0;
		value = 0;
		initComponent();
		
		pack();
		GUI.center(this);
		show();
	}
	
	private void initComponent(){
		panel = new Panel();
		
		buttonReset = new Button("reset");
		buttonPreview = new Button("preview");
		buttonApply = new Button("apply");
		
		tinta = new Label("Tonalita");
		saturazione = new Label("Saturazione");
		valore = new Label("Valore");
		
		tTinta = new TextField(10);
		tSaturazione = new TextField(10);
		tValore = new TextField(10);
		tTinta.setText("0");
		tSaturazione.setText("0");
		tValore.setText("0");
		tTinta.setEditable(false);
		tSaturazione.setEditable(false);
		tValore.setEditable(false);
		
		sTinta = new Scrollbar(Scrollbar.HORIZONTAL, 1, 0, -180, 181);
		sSaturazione = new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, -100, 101);
		sValore = new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, -100, 101);
		
		panel.setLayout(new GridLayout(4,3));
		
		panel.add(tinta);
		panel.add(tTinta);
		panel.add(sTinta);
		panel.add(saturazione);
		panel.add(tSaturazione);
		panel.add(sSaturazione);
		panel.add(valore);
		panel.add(tValore);
		panel.add(sValore);
		panel.add(buttonReset);
		panel.add(buttonPreview);
		panel.add(buttonApply);
		add(panel);
		
		buttonReset.addActionListener(this);
		buttonPreview.addActionListener(this);
		buttonApply.addActionListener(this);
		
		sTinta.addAdjustmentListener(this);
		sSaturazione.addAdjustmentListener(this);
		sValore.addAdjustmentListener(this);
	}
	
	public void setHue(int hue) {
		this.hue = hue;
	}
	public void setSaturation(int  saturation) {
		this.saturation = saturation;
	}
	public void setValue(int value) {
		this.value = value;
	}
	public int getHue(){
		return hue;
	}
	public int getSaturation(){
		return saturation;
	}
	public int getValue(){
		return value;
	}
	
	@Override
	public void actionPerformed(ActionEvent e){
		String command = e.getActionCommand();
		
		if (command.equals("reset")) {
			sTinta.setValue(0);
			sSaturazione.setValue(0);
			sValore.setValue(0);
			tTinta.setText("0");
			tSaturazione.setText("0");
			tValore.setText("0");
			setHue(0);
			setSaturation(0);
			setValue(0);
		}
		
		if (command.equals("preview")) {
			Transform tras = new Transform(imp, ip, getHue(), getSaturation(), getValue(), imp.getTitle());
			time = System.currentTimeMillis();
			ImagePlus processed = null;
			if (type == ImagePlus.COLOR_RGB) {
				processed = tras.createProcessedRGBImage();
				time = System.currentTimeMillis() - time;
				double time_sec = time / 1000.0;
				PreviewImageCS prew = new PreviewImageCS(processed, time_sec);
			}
			else {
				IJ.showStatus("impossibile applicare le modifiche");
			}
		}
		if (command.equals("apply")) {
			Undo.setup(Undo.COMPOUND_FILTER, imp);
			Transform tras = new Transform(imp, ip, getHue(), getSaturation(), getValue(), imp.getTitle());
			if (type == ImagePlus.COLOR_RGB) {
				tras.createProcessedRGBImage(imp);
			}
			else {
				IJ.showStatus("impossibile applicare le modifiche");
			}
			imp.updateAndRepaintWindow();
			imp.changes = true;
			Undo.setup(Undo.COMPOUND_FILTER_DONE, imp);
			//Html
			String path = IJ.getDirectory("image");
			J2Htm.changeTextToHtml("<H1 align = center>Tinta/Saturazione/Valore</H1>"
								   +"Path: " + path
								   +"<br>Dettagli: Tinta/Saturazione/Valore regola i valori dell'immagine"
								   +"nello spazio di colore HSV, dove: la tinta (H) si riferisce alla percezione "
								   +"visiva realtiva alla purezza del colore; la saturazione (S)"
								   +"si riferisce alla brillantezza o richezza del colore; il valore (V)"
								   +"è la luminosità relativa del colore."
								   +"L'immagine viene prima convertita dallo spazio di colore RGB a quello HSV,"
								   +"successivamente viene modificato il valore HSV di ciascun pixel."
								   +"Infine, l'immagine risultante viene convertita nuovamente nello spazio di colore RGB."
								   +"<br>Parametri:" 
								   +"<br>Tonalita': " + getHue()
								   +"<br>Aggiunge o sottrae una costante alla tinta dell'immagine. Mediante tale parametro si modifica l'intercetta di una mappatura lineare."
								   +"<br>Saturazione: " + getSaturation()
								   +"<br>Aggiunge o sottrae una costante alla saturazione dell'immagine. Mediante tale parametro si corregge l'inclinazione di una mappatura lineare."
								   +"<br>Valore: "+ getValue()
								   +"<br>Aggiunge o sottrae una costante al valore dell'immagine. Mediante tale parametro si regola l'intercetta di una mappatura lineare.");
			close();
		}
	}
	
	@Override
	public void adjustmentValueChanged(AdjustmentEvent evt) {
		Object source = evt.getSource();
		if (source == sTinta) {
			tTinta.setText("" + sTinta.getValue());
		}
		if (source == sSaturazione) {
			tSaturazione.setText("" + sSaturazione.getValue());
		}
		if (source == sValore) {
			tValore.setText("" + sValore.getValue());
		}
		setHue(Integer.parseInt(tTinta.getText()));
		setSaturation(Integer.parseInt(tSaturazione.getText()));
		setValue(Integer.parseInt(tValore.getText()));
		repaint();
	}
}
class Transform {
	private ImageProcessor ip;
	private ImagePlus imp;
	private int hue, saturation, value;
	private String title;
	
	public Transform(ImagePlus imp, ImageProcessor ip, int hue, int saturation, int value, String title) {
		this.imp = imp;
		this.ip = ip;
		this.hue = hue;
		this.saturation = saturation;
		this.value = value;
		this.title = title;
	}
	
	private int convertValue(double valuePixel, int value){
		return (int)Math.round((Math.abs(valuePixel) * value)/100);
		
	}
	
	private int[] applyTransform(int[] pixels){
		int[] output = new int[pixels.length];
		for (int i = 0; i < pixels.length; i++) {
			int c = pixels[i];

			int r = (c&0xff0000) >> 16;
			int g = (c&0x00ff00) >> 8;
			int b = (c&0x0000ff);
			
			double[] arrayHSV = new Convert().RGBtoHSV(r, g, b);
			
			double hue = arrayHSV[0] + convertValue(arrayHSV[0], this.hue);
			double saturation = arrayHSV[1] + convertValue(arrayHSV[1], this.saturation);
			double value = arrayHSV[2] + convertValue(arrayHSV[2], this.value);
			
			int[] arrayRGB = new Convert().HSVtoRGB(hue, saturation, value);
			if (arrayRGB[0] > 255) {
				arrayRGB[0] = 255;
			}
			if (arrayRGB[1] > 255) {
				arrayRGB[1] = 255;
			}
			if (arrayRGB[2] > 255) {
				arrayRGB[2] = 255;
			}
			output[i] = ((arrayRGB[0] & 0xff) << 16) + ((arrayRGB[1] & 0xff) << 8) + (arrayRGB[2] & 0xff);			
		}
		return output;
	}
	public ImagePlus createProcessedRGBImage(){
		ImageProcessor processed_ip = ip.crop();
        ImagePlus processed = imp.createImagePlus();
        processed.setProcessor(title, processed_ip);
        int[] processed_pixels = (int[])processed_ip.getPixels();
        int[] output = applyTransform(processed_pixels);
        for (int i = 0; i < output.length; i++) {
			processed_pixels[i] = output[i];
		}
		return processed;
	}
	public void createProcessedRGBImage(ImagePlus img){
		int[] processed_pixels = (int[])(img.getProcessor()).getPixels();
        int[] output= applyTransform(processed_pixels);
        for (int i=0; i<output.length; i++) {
			processed_pixels[i] = output[i];
		}
	}	
}
//end clas transform

/**
 class PreviewImageCS per l'anteprima dell'immagine
 */
class PreviewImageCS implements ActionListener
{
	private ImageCanvas canvas;
	private Panel panelTime;
	private ImagePlus im;
	
	public PreviewImageCS(ImagePlus img, double time){
        im = img;
        canvas = new ImageCanvas(im);
        ImageWindow imgWin = new ImageWindow(im);
        imgWin.setResizable(false);
        imgWin.setSize(canvas.getSize().width+150,canvas.getSize().height+150);
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        imgWin.setLayout(gridbag);
        
        //Panel Canvas
        c.gridx = 0;
        int y = 0;
        c.gridy = y++;
        c.insets = new Insets(10, 10, 0, 10);
        gridbag.setConstraints(canvas, c);
        imgWin.add(canvas);
        
        //Panel Time
        Panel panelTime = new Panel();
        c.gridy = y++;
        c.insets = new Insets(2, 10, 0, 10);
        gridbag.setConstraints(panelTime, c);
        Label timeLab = new Label("Elapsed Time: ");
        timeLab.setFont(new Font("SansSerif", Font.PLAIN, 12));
        panelTime.add(timeLab);
        Label timeLab2 = new Label(new Double(time).toString()+" seconds");
        timeLab2.setFont(new Font("SansSerif", Font.PLAIN, 12));
        panelTime.add(timeLab2);
        imgWin.add(panelTime);
        
        Panel panelHisto = new Panel();
        c.gridy = y++;
        c.insets = new Insets(2, 10, 0, 10);
        gridbag.setConstraints(panelHisto, c);
        Button histo = new Button("View Histogram");
        histo.addActionListener(this);
        panelHisto.add(histo);
        imgWin.add(panelHisto);
        imgWin.show();
	}
	
	public void actionPerformed(ActionEvent e) 
	{
        HistogramWindow isto=new HistogramWindow(im.getTitle(),im,256);
		isto.show();
	}
}
//end class PreviewImageCS

/**
 class convert per convertire i pixel da RGB a HSV
 */
class Convert {
	
	public Convert(){}
	
	public static double[] RGBtoHSV(double r, double g, double b){
		
		double h, s, v;
		double min, max, delta;
		
		min = Math.min(Math.min(r, g), b);
		max = Math.max(Math.max(r, g), b);
		
		// V
		v = max;
		
		delta = max - min;
		
		// S
		if( max != 0 )
			s = delta / max;
		else {
			s = 0;
			h = -1;
			return new double[]{h,s,v};
		}
		
		// H
		if( r == max )
			h = ( g - b ) / delta; // between yellow & magenta
		else if( g == max )
			h = 2 + ( b - r ) / delta; // between cyan & yellow
		else
			h = 4 + ( r - g ) / delta; // between magenta & cyan
		
		h *= 60;    // degrees
		
		if( h < 0 )
			h += 360;
		
		return new double[]{h, s, v};
	}
	
	public static int[] HSVtoRGB(double h, double s, double	v){
		int i, r, g, b, p, q, t;
		double f;
		if( s == 0 ) {
			r = g = b = (int)v;
			return new int[]{r, g, b};
		}
		h /= 60;
		i = (int)Math.floor( h );
		f = h - i;
		p = (int)Math.round(v * ( 1 - s ));
		q = (int)Math.round(v * ( 1 - s * f ));
		t = (int)Math.round(v * ( 1 - s * ( 1 - f ) ));
		switch( i ) {
			case 0:
				r = (int)v;
				g = (int)t;
				b = (int)p;
				break;
			case 1:
				r = (int)q;
				g = (int)v;
				b = (int)p;
				break;
			case 2:
				r = (int)p;
				g = (int)v;
				b = (int)t;
				break;
			case 3:
				r = (int)p;
				g = (int)q;
				b = (int)v;
				break;
			case 4:
				r = (int)t;
				g = (int)p;
				b = (int)v;
				break;
			default:
				r = (int)v;
				g = (int)p;
				b = (int)q;
				break;
		}
		return new int[]{r, g, b};
	}
	class J2Htm {
		public void changeTextToHtml(String inputTxtFile){
			String [] temp = inputTxtFile.split(".");
			String s,formName = "testForm";
			try{
				
				FileWriter htmlFile = new FileWriter("tsv.htm");
				PrintWriter htmlPrintWriter = new PrintWriter(htmlFile);
				htmlPrintWriter.println("<html>");
				htmlPrintWriter.println("<head>");
				htmlPrintWriter.println("<script>");
				
				htmlPrintWriter.println("</script>");
				htmlPrintWriter.println("</head>");
				htmlPrintWriter.println("<form name ="+formName+" >");
				htmlPrintWriter.println("<body>");
				
				htmlPrintWriter.println(inputTxtFile);
				htmlPrintWriter.println("</body>");
				htmlPrintWriter.println("</form>");
				htmlPrintWriter.println("</html>");
				
				htmlPrintWriter.close();
				
				
			}
			catch(Exception e){e.printStackTrace();}
			
		}
		
	}

}
//end class Convert