package org.khelekore.jsizer;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JFileChooser;

/** An action that pops up a dialog that lets the user select a file
 *  containing classes to be colored.
 */
class ColorAction extends AbstractAction {
    private static final long serialVersionUID = 1;
    private JFrame f;
    private SizePanel sp;
    private File lastFile;

    // TODO: maybe let the user choose color
    // TODO: maybe add more colors.
    private static final Color[] colors = {Color.BLUE, Color.RED, Color.GREEN, 
					   Color.MAGENTA, Color.ORANGE};
    private int currentColor = 0;

    public ColorAction (JFrame f, SizePanel sp) {
	super ("Color classes...");
	this.f = f;
	this.sp = sp;
    }

    public void actionPerformed (ActionEvent e) {
	JFileChooser chooser = new JFileChooser ();
	if (lastFile != null)
	    chooser.setCurrentDirectory (lastFile.getParentFile ());
	chooser.setFileSelectionMode (JFileChooser.FILES_ONLY);
	int returnVal = chooser.showDialog (f, "Select file");
	if (returnVal != JFileChooser.APPROVE_OPTION)
	    return;
	File selected = chooser.getSelectedFile ();
	lastFile = selected;
	FileInputStream fis = null;
	InputStreamReader isr = null;
	BufferedReader br = null;
	Color c = colors[currentColor++];
	currentColor %= colors.length;
	try {
	    fis = new FileInputStream (selected);
	    isr = new InputStreamReader (fis, "UTF-8");
	    br = new BufferedReader (isr);
	    String line;
	    while ((line = br.readLine ()) != null) {
		line = line.trim ();
		if (line.equals (""))
		    continue;
		sp.addColor (line, c);
	    }
	} catch (IOException ex) {
	    ex.printStackTrace ();
	} finally {
	    close (br);
	    close (isr);
	    close (fis);
	}
	sp.rebuild ();
    }
    
    private void close (Closeable c) {
	if (c == null)
	    return;
	try {
	    c.close ();
	} catch (IOException e) {
	    e.printStackTrace ();
	}
    }
}
