package smart_gs.swingui.toolbar.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;

import javax.swing.JFileChooser;

import smart_gs.logical.LineSegmentForEdit;
import smart_gs.logical.Preference;
import smart_gs.logical.Spread;
import smart_gs.smleditor.swingui.LineSegEditor;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.util.Pair;
import smart_gs.util.SegfoToLineConverter;
import smart_gs.util.XMLToLineConverter;
import sml_editor.logical.LineDirection;

public class ReadXMLLineSegmentFileAction implements ActionListener {
	private LineSegEditor editor;
	private Spread spread;
	private LineDirection lineDirection;
	private List<LineSegmentForEdit> lines = null;
	private JFileChooser chooser;
	private static String defaultFilePathInString ="";

	public ReadXMLLineSegmentFileAction(LineSegEditor parent) {
		this.editor = parent;
		this.spread = this.editor.getSpread();
		String folderpath = null;
		if (defaultFilePathInString.isEmpty()) {
			folderpath = Preference.getInstance().getImageFolderPathString() + spread.getFolderPath();
			defaultFilePathInString = folderpath + spread.getFileNameWithoutExtension() + ".xml";
		} 
		this.chooser = new JFileChooser(folderpath);
		this.chooser.setSelectedFile(new File(defaultFilePathInString));		
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		chooser.setMultiSelectionEnabled(false);
		chooser.setFileFilter(new XmlFileFilter());
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		int input = chooser.showOpenDialog(WorkspaceWindow.getInstance());
		if (input == JFileChooser.CANCEL_OPTION) {
			return;
		}
		
		File file = chooser.getSelectedFile();
		
		if (file == null) return;
		
		defaultFilePathInString = file.getAbsolutePath();
		
		Pair<LineDirection,List<LineSegmentForEdit>> tmp = new XMLToLineConverter(spread).getLinesForEdit(file);
		
		if (tmp == null) return;

		lines = tmp.getRight();
        editor.setLineDirectionForEdit(lineDirection);
        editor.setLinesForEdit(lines);
        editor.rewriteLineSegIndexes();
        editor.repaint();
	}

}
