/* $Id: AddSpreadsAction.java 339 2011-09-07 03:01:03Z shayashi $ */
package smart_gs.swingui.tree.action;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import smart_gs.logical.Preference;
import smart_gs.logical.SpreadDirectory;
import smart_gs.logical.SpreadTree;
import smart_gs.logical.filter.ImageFileFilter;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.util.CanonicalPathString;
import smart_gs.util.GSStandardPath;

public class AddSpreadsAction implements ActionListener{
	protected File openDirectory;
	protected SpreadTree tree = SpreadTree.getInstance();
	protected SpreadDirectory spreadDirectory;
	String imageFolderPath = GSStandardPath.toStandardOnCurrentOS(CanonicalPathString.get(new File(Preference.getInstance().getImageFolderPathString())));
	File imageFolder = new File(Preference.getInstance().getImageFolderPathString());

	
	public AddSpreadsAction(File openDirectory,SpreadTree tree,SpreadDirectory spreadDirectory){
		this.openDirectory = openDirectory;
		this.tree = tree;
		this.spreadDirectory = spreadDirectory;

	}
	
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser(openDirectory);
		chooser.setMultiSelectionEnabled(true);
		chooser.setFileFilter(new ImageFileFilter());
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		int input = chooser.showOpenDialog(WorkspaceWindow.getInstance());
		if (input == JFileChooser.CANCEL_OPTION) {
			return;
		}
		
		File files[] = chooser.getSelectedFiles();
		int size = files.length;
		
		for (int count = 0; count <size; count++) {
			File file = files[count];
//			2011.04.08 shayashi
			String fileToAddPath = CanonicalPathString.get(file);
			fileToAddPath = GSStandardPath.toStandardOnCurrentOS(fileToAddPath);
			if(!fileToAddPath.startsWith(imageFolderPath)){
				JOptionPane.showMessageDialog(new Frame(), 
						String.format("Image file %s \n is not in Image Folder %s.",fileToAddPath,imageFolderPath),"Information",JOptionPane.DEFAULT_OPTION);
				return;
			}
			String openDirPath = CanonicalPathString.get(openDirectory);
			openDirPath = GSStandardPath.toStandardOnCurrentOS(openDirPath);
			String path = openDirPath + "/" + file.getName();
			if(!path.equals(fileToAddPath)){
				JOptionPane.showMessageDialog(new Frame(), 
						String.format("Image file %s \n is not in the directory specified",file.toString()),"Information",JOptionPane.DEFAULT_OPTION);
				return;
			}
			this.tree.addImage(file);
		}
	}
}
