/* $Id: OpenActionListener.java 236 2011-06-23 15:18:05Z shayashi $ */
package smart_gs.swingui.toolbar.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Stack;

import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import smart_gs.swingui.WorkspaceWindow;
import smart_gs.logical.Preference;
import webdav.WebDavChooser;
import webdav.WebDavDownLoadEvent;
import webdav.WebDavListenerAction;
import webdav.WebDavProcessor;
public class OpenActionListener implements ActionListener {
	protected int mode = 0;
	public OpenActionListener(int mode){
		this.mode = mode;
	}

	public void actionPerformed(ActionEvent e) {

		//2009/01/23 North Grid
		Preference preference = Preference.getInstance();
		//2008/9/8 North Grid
		//更新時に確認ダイアログを表示する仕組みを追加
		WorkspaceWindow window = WorkspaceWindow.getInstance();
		if( WorkspaceWindow.isUpdated() ){
			String filename = null;
			if(window.getLastsave() == 0){
				if(window.getCurrentFile() != null){
					filename = window.getCurrentFile().getName();
				}
			}else{
				WebDavDownLoadEvent webDavDownLoadEvent = window.getWebDavDownLoadEvent();
				if(webDavDownLoadEvent != null){
					filename = webDavDownLoadEvent.getDownloaname();
				}
			}
			int input = JOptionPane.showConfirmDialog(window,  
					(filename == null ? 
							"Save the edited contents?" :
							"\""+ filename + "\"   Save this file?")
					);
			
			if (input == JOptionPane.OK_OPTION) {
				
				if(window.getLastsave() == 0){
					if( window.saveAll() == false ) return;
				}else{
					WebDavListenerAction webDavListenerAction = new WebDavListenerAction();
					webDavListenerAction.save();
				}
			} else if (input == JOptionPane.NO_OPTION) {

			} else if (input == JOptionPane.CANCEL_OPTION) {
				return;
			}
		}		
		
		//2007/10/7 kazuhiro kobayashi
		//2009/01/23 North Grid
		if(mode == 1){
			WebDavListenerAction webDavListenerAction = new WebDavListenerAction();
			webDavListenerAction.open();
		}else{
			String currentDirectory = preference.getGsFolderPathString();
			
			JFileChooser chooser = new JFileChooser(currentDirectory);
			chooser.setFileFilter(new GSFileFilter());
			
			int input = chooser.showOpenDialog(WorkspaceWindow.getInstance());
			if(input == JFileChooser.CANCEL_OPTION){
				return;
			}
			File file = chooser.getSelectedFile();
			WorkspaceWindow.getInstance().restore(file);
			WorkspaceWindow.getInstance().setFileOpened(true);
			WorkspaceWindow.getInstance().autosave(file);
			WorkspaceWindow.getInstance().unlock();
			window.setLastsave(0);
		}
	}
	
}
