package smart_gs.swingui.toolbar.action;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

import org.jsoup.helper.StringUtil;

import smart_gs.drawing_tool.drawing_mode.LineSegEditorDivideMode;
import smart_gs.logical.LineSegmentForEdit;
import smart_gs.smleditor.swingui.LineSegEditor;

public class LineSegEditorDivideModeFrame extends Frame{

	private LineSegEditor editor;
	private final String iputExp = "([ 	]*[0-9]+[ 	]*)+";
	private Pattern patternInputExp;
	private ArrayList<Integer> selectedIndexes;

	public LineSegEditorDivideModeFrame(LineSegEditor editor, ArrayList<Integer> selectedIndexes) {
		this.editor = editor;
		this.selectedIndexes = selectedIndexes;
		
		if (editor.getLinesForEdit() == null) return;
			
        String selectedIndexesString = new String();
		
		for (int i : this.selectedIndexes) selectedIndexesString += i + " ";
		
		this.setLayout(new BorderLayout());
		String input = JOptionPane.showInputDialog("Specify line segment indexes", selectedIndexesString);

		if(StringUtil.isBlank(input)){
			return;
		}
		patternInputExp = Pattern.compile(iputExp);
		Matcher matcherZenkakuOrAscii = patternInputExp.matcher(input);
		if (!matcherZenkakuOrAscii.matches()) {
			JOptionPane.showMessageDialog(editor,"Input is incorrect");
		}
		
		String[] str = input.split("[ ]+");
		
		List<LineSegmentForEdit> lines = editor.getLinesForEdit();
		int length = lines.size();
		
		if (length == 0) return;
		
		this.selectedIndexes = new ArrayList<Integer>();

		for (String indexToken : str) {
			int index = Integer.parseInt(indexToken);
			if (index >= length) {
				JOptionPane.showMessageDialog(null,"Index " + index + "is out of range");
				return;
			}
			this.selectedIndexes.add(index);

		}

		Collections.sort(this.selectedIndexes);
		Collections.reverse(this.selectedIndexes);

		LineSegEditorDivideMode mode = new LineSegEditorDivideMode(editor,this.selectedIndexes);
		this.editor.setMode(mode);
	}
}