package smart_gs.swingui.toolbar.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

import smart_gs.logical.LineSegmentForEdit;
import smart_gs.logical.Spread;
import smart_gs.smleditor.swingui.LineSegEditor;

public class LineSegEditorChangeIndexActionListener implements ActionListener {
	LineSegEditor editor;
	private final String iputExp = "([ 	]*[1-9][0-9]*[ 	]*>[ 	]*[1-9][0-9]*[ 	]*[ 	]*,[ 	]*)*[ 	]*[1-9][0-9]*[ 	]*>[ 	]*[1-9][0-9]*[ 	]*";
	private Pattern patternInputExp;
	
	public LineSegEditorChangeIndexActionListener(LineSegEditor editor) {
		this.editor = editor;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		editor.pushUndoStack();
		String input = JOptionPane.showInputDialog("Specify change. E.g. 7>3 to change 7tn line to 3rd\nTo change simultaneously: 7>3, 3>4,...", "");
		if(input == null){
			return;
		}
		
		patternInputExp = Pattern.compile(iputExp);
		Matcher matcherZenkakuOrAscii = patternInputExp.matcher(input);
		if (!matcherZenkakuOrAscii.matches()) {
			JOptionPane.showMessageDialog(editor,"Input is incorrect.");
		}
		
		
		int index = input.indexOf('>');
		int oldIndex = Integer.parseInt(input.substring(0, index));
		int newIndex = Integer.parseInt(input.substring(index+1,input.length()));
		
		List<LineSegmentForEdit> lines = editor.getLinesForEdit();

		if (oldIndex == newIndex) return;
		int length = lines.size();
		if (oldIndex >= length) {
			JOptionPane.showMessageDialog(null,"Old index is out of range");
			return;
		}
		if (newIndex >= length) {
			JOptionPane.showMessageDialog(null,"New index is out of range");
			return;
		}
		LineSegmentForEdit tmp = lines.get(oldIndex);
		lines.remove(oldIndex);
		lines.add(newIndex,tmp);
		editor.rewriteLineSegIndexes();
		editor.repaint();
	}
}
