package smart_gs.swingui.toolbar.action;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import smart_gs.drawing_tool.LineSegEditorImageLabel;
import smart_gs.drawing_tool.drawing_mode.LineSegEditorDivideMode;
import smart_gs.drawing_tool.drawing_mode.LineSegEditorDrawMode;
import smart_gs.drawing_tool.drawing_mode.LineSegEditorDrawMode;
import smart_gs.drawing_tool.drawing_mode.LineSegEditorSemiAutomaticMode;
import smart_gs.drawing_tool.state.DefaultState;
import smart_gs.drawing_tool.view.View;
import smart_gs.logical.LineSegmentForEdit;
import smart_gs.logical.Spread;
import smart_gs.smleditor.swingui.LineSegEditor;
import smart_gs.swingui.toolbar.LineSegEditorToolBar;

public class LineSegEditorDivideActionListener implements ActionListener {
	LineSegEditor editor;
	LineSegEditorToolBar toolbar;
	private final String iputExp = "[ 	]*[0-9]+[ 	]*";
	private Pattern patternInputExp;
	
	public LineSegEditorDivideActionListener(LineSegEditor editor,LineSegEditorToolBar toolbar) {
		this.editor = editor;
		this.toolbar = toolbar;
	}
	public void actionPerformed(ActionEvent e) {
		editor.pushUndoStack();
		editor.setMode(new LineSegEditorDrawMode(editor));
		int selectedIndex = editor.selectedIndex();
		String input = JOptionPane.showInputDialog("Specify a line segment index", (selectedIndex >=0 )?selectedIndex:"");
		if(input == null){
			return;
		}
		patternInputExp = Pattern.compile(iputExp);
		Matcher matcherZenkakuOrAscii = patternInputExp.matcher(input);
		if (!matcherZenkakuOrAscii.matches()) {
			JOptionPane.showMessageDialog(editor,"Input is incorrect");
		}
		int index = Integer.parseInt(input);
		
		if (editor.getLinesForEdit() == null) {
			
		}

		List<LineSegmentForEdit> lines = editor.getLinesForEdit();
		int length = lines.size();
		if (index >= length) {
			JOptionPane.showMessageDialog(null,"Index is out of range");
			return;
		}

		List<LineSegmentForEdit> newlines = new ArrayList<LineSegmentForEdit>();
		LineSegmentForEdit selectedLineSeg = lines.get(index);
		View view = selectedLineSeg.getView();
		view.setIsSelected(true);
		newlines.add(selectedLineSeg);
		editor.setLinesForEdit(newlines);
		LineSegEditorDivideMode mode = new LineSegEditorDivideMode(editor);
		mode.giveSelectedLine(newlines);
		mode.giveOriginalLines(lines);
		mode.giveSelectedLineSegIndex(index);
		mode.giveLineSegEditor(this.editor);
		mode.giveLineSegEditorToolBar(this.toolbar);
		editor.setMode(mode);
		editor.getLineSegEditorCanvas().getLineSegEditorImageLabel().setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));	
		editor.repaint();
	}
}