package rapanui.ui.controls;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.FocusEvent;

import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

import rapanui.dsl.Parser;

public class SyntaxTextField extends JTextField implements DocumentListener {
	private static final long serialVersionUID = 1L;

	private static final Font mathFont = new Font("Courier New", Font.PLAIN, 14);
	private static final Border invalidBorder = new LineBorder(Color.red);

	private boolean isValid = true;
	private final ParsingMode parsingMode;

	private final Border defaultBorder;

	public SyntaxTextField(ParsingMode mode) {
		this(mode, null);
	}

	public SyntaxTextField(ParsingMode mode, Document model /* may be null */) {
		super(model, null, 0);
		setFont(mathFont);
		this.parsingMode = mode;
		getDocument().addDocumentListener(this);
		defaultBorder = getBorder();
	}

	public static enum ParsingMode {
		Term,
		Formula
	}

	protected void verify() {
		try {
			if (parsingMode == ParsingMode.Term)
				Parser.getInstance().parseTerm(getText());
			else if (parsingMode == ParsingMode.Formula)
				Parser.getInstance().parseFormula(getText());
			isValid = true;
			setBorder(defaultBorder);
		} catch (IllegalArgumentException e) {
			isValid = false;
			setBorder(getText().isEmpty() ? defaultBorder : invalidBorder);
		}
	}

	public boolean isValid() {
		return isValid;
	}

	@Override
	protected void processFocusEvent(FocusEvent e) {
		if (!e.isTemporary() && e.getID() == FocusEvent.FOCUS_LOST)
			verify();
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		if (!isValid)
			verify();
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		if (!isValid)
			verify();
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		if (!isValid)
			verify();
	}
}

@@ -1131,19 +1131,14 @@
 %7B%0A%09%09
-try %7B%0A%09%09%09if
+switch
  (pa
@@ -1150,34 +1150,40 @@
 Mode
- == ParsingMode.
+) %7B%0A%09%09%09case 
 Term
-)
+:
 %0A%09%09%09%09
+isValid = 
 Pars
@@ -1195,25 +1195,28 @@
 tInstance().
-p
+canP
 arseTerm(get
@@ -1231,57 +1231,47 @@
 %0A%09%09%09
-else if (parsingMode == ParsingMode.
+%09break;%0A%09%09%09case 
 Formula
-)
+:
 %0A%09%09%09%09
+isValid = 
 Pars
@@ -1287,17 +1287,20 @@
 tance().
-p
+canP
 arseForm
@@ -1322,94 +1322,29 @@
 %0A%09%09%09
-isValid = true;%0A%09%09%09setBorder(defaultBorder);%0A%09%09%7D catch (IllegalArgumentException e) %7B%0A
+%09break;%0A%09%09%09default:%0A%09
 %09%09%09i
@@ -1360,16 +1360,19 @@
 false;%0A%09
+%09%7D%0A
 %09%09setBor
@@ -1394,16 +1394,27 @@
 sEmpty()
+ %7C%7C isValid
  ? defau
@@ -1440,20 +1440,16 @@
 order);%0A
-%09%09%7D%0A
 %09%7D%0A%0A%09pub

use canParse* methods