package ash.gui.core;
import java.io.File;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JFileChooser;
import ash.util.FileUtil;

@SuppressWarnings("serial")
public class AshFileChooser extends AshPanel implements ActionListener {
	private JTextField field;
	public JTextField getField() { return field; }
	private JButton rootButton = new JButton("Бе");
	private int mode = JFileChooser.FILES_ONLY;
	public AshFileChooser(String root, int size, char mode) {
		setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
		rootButton.addActionListener(this);
		//add(field = field(root, size), rootButton);	// BUG?, CA071026
		add(field = field(root, size));
		add(rootButton);
		switch(mode) {
		case 'f': this.mode = JFileChooser.FILES_ONLY; break;
		case 'd': this.mode = JFileChooser.DIRECTORIES_ONLY; break;
		case 'b': this.mode = JFileChooser.FILES_AND_DIRECTORIES; break;
		}
	}
	public String getText() { return field.getText(); }
	public void setText(String text) { field.setText(text); }
	public void actionPerformed(ActionEvent ae) {
		File prevFile = GUIAdapter.findFile(getText());
		if(prevFile == null) prevFile = new File(".");
		File f = chooseDirectory(prevFile);
		if(f != null) setText(FileUtil.getPath(f));
	}
	private File chooseDirectory(File prevFile) {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(prevFile);
		chooser.setSelectedFile(prevFile);
		chooser.setFileSelectionMode(mode);
		int return_val = chooser.showOpenDialog(this);
		if(return_val == JFileChooser.APPROVE_OPTION)
			return chooser.getSelectedFile();
		return null;
	}
}
