package smart_gs.swingui.toolbar.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import smart_gs.image_search.logical.TextType;
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;

public class SaveLineSegmentsInSegfoFormatAction implements ActionListener {
	private LineSegEditor editor;
	private Spread spread;
	private String file_name;
	private JFileChooser chooser;

	public SaveLineSegmentsInSegfoFormatAction(LineSegEditor parent) {
		this.editor = parent;
		this.spread = this.editor.getSpread();
		this.file_name = this.spread.getFileName();
		this.chooser = new JFileChooser(Preference.getInstance().getImageFolderPathString() + spread.getFolderPath());
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		chooser.setMultiSelectionEnabled(false);
		chooser.setFileFilter(new SegfoFileFilter());
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		int input = chooser.showOpenDialog(WorkspaceWindow.getInstance());
		if (input == JFileChooser.CANCEL_OPTION) {
			return;
		}
		
		File file = chooser.getSelectedFile();
		if (file.exists()) {
			int ans = JOptionPane.showConfirmDialog(editor,String.format("File %s exists. Overwrite?",file.toString()));
			if (ans == JOptionPane.NO_OPTION) return;
		}
			
		try{
			FileOutputStream fstream = new FileOutputStream(file);
			OutputStreamWriter  out = new OutputStreamWriter(fstream);
			PrintWriter pw = new PrintWriter(out);
			
			pw.printf(file_name + "%n");

			if (Preference.getInstance().getTextType()==TextType.HORIZONTAL)
				pw.printf("Horizontal%n");
			else 
				pw.printf("Vertical%n");
			List<LineSegmentForEdit> lines = editor.getLinesForEdit();
			for (int i=0;i<lines.size();i++) {
				LineSegmentForEdit line = lines.get(i);
				List<Point2D> points = line.getPoints();
				for (int j=0;j<points.size();j++) {
					Point2D point = points.get(j);
					pw.printf("%6d",(int)point.getX());
					pw.printf("%6d",(int)point.getY());
				}
				pw.printf("%6d%n",-1);
			}
			pw.printf("-99999%n");
			pw.close();
		}catch (Exception e){
			 e.printStackTrace();
		}
		
	}

}
