package smart_gs.menu.action;

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.OldGSFileConverter;
import smart_gs.logical.Preference;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.swingui.toolbar.action.GSFileFilter;
import webdav.WebDavDownLoadEvent;
import webdav.WebDavListenerAction;

public class OpenOldVersionActionListener implements ActionListener {
	protected int mode = 0;
	public OpenOldVersionActionListener(int mode){
		this.mode = mode;
	}

	public void actionPerformed(ActionEvent e) {

		Preference preference = Preference.getInstance();
		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;
			}
		}		
		
		if(mode == 1){
			WebDavListenerAction webDavListenerAction = new WebDavListenerAction();
			webDavListenerAction.open();
		}else{
			String currentDirectory = preference.getGsFolderPathString();
			
			JFileChooser chooser = new JFileChooser(currentDirectory);
			chooser.setFileFilter(new GSFileFilter("gs"));
			
			int input = chooser.showOpenDialog(WorkspaceWindow.getInstance());
			if(input == JFileChooser.CANCEL_OPTION){
				return;
			}
			File gsFile = chooser.getSelectedFile();
			OldGSFileConverter fc = new OldGSFileConverter(gsFile);
			File gsxFile = fc.convertGSFile();
			WorkspaceWindow.getInstance().restore(gsxFile);
			WorkspaceWindow.getInstance().setFileOpened(true);
			WorkspaceWindow.getInstance().autosave(gsxFile);
			WorkspaceWindow.getInstance().unlock();
			window.setLastsave(0);
		}
	}
	
}
