package application;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.prefs.Preferences;

import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class LoadAction implements ActionListener {
	private JFileChooser fc;
	private JFrame parent;
	private JLabel loadlabel;
	private JComponent button = null;

	public LoadAction(JFrame parent, JLabel loadlabel) {
		this.parent = parent;
		this.loadlabel = loadlabel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		button = (JComponent)e.getSource();
		button.setEnabled(false);

		loadlabel.setText("undefined input");
		
		Preferences prefs = Preferences.userRoot().node(getClass().getName());
		String LAST_USED_FOLDER = "LAST_USED_INPUT_FOLDER";
		fc = new JFileChooser(prefs.get(LAST_USED_FOLDER,
			    new File(".").getAbsolutePath()));
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		fc.setPreferredSize( new Dimension(640, 800) );

		int returnVal = fc.showOpenDialog(parent);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File path = fc.getSelectedFile();
			prefs.put(LAST_USED_FOLDER, path.toString());
			System.out.println(path);
			if (TD.setInputPath(path)) {
				loadlabel.setText(path.toString());
				Thread t = new Thread(new Runnable() {
					@Override
					public void run() {
						TD.loadImages(LoadAction.this);
						done();
					}} );
				t.start();
			}
		}
		else {
			button.setEnabled(true);
		}
	}

	void progress(final String msg) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				if(loadlabel != null)
					loadlabel.setText(msg);
			}
		});

	}

	void done() {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				if(button != null)
					button.setEnabled(true);
			}
		});

	}
}
