/* $Id: AddSpreadsAction.java 131 2011-03-25 15:25:12Z 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 java.io.IOException;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.commons.io.FileUtils;

import smart_gs.logical.GSResource;
import smart_gs.logical.Preference;
import smart_gs.logical.SpreadDirectory;
import smart_gs.logical.SpreadTree;
import smart_gs.logical.filter.ImageFileDirFilterForSpreadTree;
import smart_gs.logical.filter.ImageFileFilter;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.util.CanonicalPathString;
import smart_gs.util.GSImageFileUtils;
import smart_gs.util.GSPathStringGrammarChecker;
import smart_gs.util.GSStandardPath;
import smart_gs.util.FileCopy;
import smart_gs.util.StringUtils;

public class ImportImagesAction implements ActionListener{
	protected DefaultMutableTreeNode parentTreeNode;
	protected SpreadDirectory spreadDirectory;
	protected SpreadTree tree;
	protected SpreadDirectory parentSpreadDir;
	protected File targetDir;

	public ImportImagesAction(DefaultMutableTreeNode parentTreeNode, SpreadTree tree){
		this.parentTreeNode = parentTreeNode;
		this.spreadDirectory = spreadDirectory;
		this.tree = tree;
		parentSpreadDir = (SpreadDirectory) parentTreeNode.getUserObject();
		targetDir = parentSpreadDir.getFile();
	}
	
	// TODO 2011.04.11 一つずつ、addImage -> addLoadImage で　Spreadが付け加わっている。
	//　つまり、AutomaticNumberingが毎回よばれている。これをrefactorせよ。
	//　addImages(File[])　を作れば良い。
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser("/");
		chooser.setMultiSelectionEnabled(true);
		chooser.setFileFilter(new ImageFileFilter());
		tree.expandRow(0);
		
		int input = chooser.showOpenDialog(WorkspaceWindow.getInstance());
		if (input == JFileChooser.CANCEL_OPTION) {
			return;
		}
		
		File files[] = chooser.getSelectedFiles();
		int size = files.length;
		
//		TODO Read XML files as well optionally. 2011.06.22 shayashi 
		
		for (int count = 0; count <size; count++) {
			File file = files[count];
			String fullname = file.getName();
			if (!GSPathStringGrammarChecker.isFileDirIdentifier(fullname)) {
				JOptionPane.showMessageDialog(null, String.format("Error: name %s cannot be used in SMART-GS.",fullname));
				continue;
			}
			int lastPeriodIndex = fullname.lastIndexOf(".");
			int length = fullname.length();
			if (lastPeriodIndex < 0 || lastPeriodIndex == length-1){
				JOptionPane.showMessageDialog(null, String.format("Error: format type of %s is not available.",fullname));
				continue;
			}
			String extension = fullname.substring(lastPeriodIndex+1);
			if (!GSImageFileUtils.isSupportedFormat(extension)) {
				JOptionPane.showMessageDialog(null, String.format("Error: file format %s of %s is not supported.",extension,fullname));
				continue;
			}
			String name = fullname.substring(0,fullname.lastIndexOf("."));
			Enumeration<DefaultMutableTreeNode> enm = parentTreeNode.children();
			boolean nameExists = false;
			while (enm.hasMoreElements()){
				String tmp = ((GSResource)(enm.nextElement()).getUserObject()).getName();
				if (tmp.equalsIgnoreCase(name)) {
					nameExists = true;
					JOptionPane.showMessageDialog(null, 
							String.format("Error: name %s already exists in %s\nRemark: name equality check is case-senseless for Windows File Systems",tmp, tree.makePathString(parentTreeNode.getPath())));
					break;
				}
			}

			if (!nameExists) {
				try {
					FileUtils.copyFileToDirectory(file,targetDir);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				File targetFile = new File(targetDir,fullname);
				tree.addImage(targetFile);
				File sourceDscDir = new File(file.getParentFile(),"dsc");
				if (sourceDscDir.exists()){
					File sourceDscFile = new File(sourceDscDir,name + "dsc");
					if (sourceDscFile.exists()){
						File targetDscDir = new File(targetDir,"dsc");
						targetDscDir.mkdir();
						if (!targetDscDir.exists()){
							System.out.printf("Error: %s does not exist\n",targetDscDir);
							return;
						};
						FileCopy.copy(sourceDscFile,targetDscDir);
					}
				}
				
			}
		}
	}
}