package gve.calc.formula;

import java.awt.*;

public class Identifier extends Part {
	private String string;

	// Create an empty Identifier
	public Identifier() {
		string = "";
	}

	public Identifier(char value) {
		string = ""+value;
	}

	// Create an Identifier with predefined value
	public Identifier(String value) {
		string = value;
	}

	public Object clone() {
		return new Identifier(string);
	}

	public void setString(String str) {
		string = str;
		MVC.changed(this);
	}

	public String getString() { return string; }

	public boolean isNumeric() {
		try { new Double(string); }
		catch (NumberFormatException exc) { return false; }
		return true;
	}

	public Part evaluate(Evaluator ev) {
		Object eval = ev.getValue(string);
		if (eval instanceof Formula)
			return (Part)((Formula)eval).getRootPart().clone();
		if (eval instanceof Part)
			return (Part)((Part)eval).clone();
		if (eval == null) return (Part)clone();
		System.out.println("Warning: cannot evaluate "+eval);
		return (Part)eval;	// oops
	}

	public boolean isEmpty() {
		if (string == null) return true;
		return string.equals("");
	}

	public String toString() {
		return getClass().getName()+"["+string+"]";
	}

	public void write(java.io.Writer w) throws java.io.IOException {
		super.write(w);
		w.write(string);
		w.write('\n');
	}

	public static Part read(java.io.BufferedReader r) throws java.io.IOException,
			ClassNotFoundException,NoSuchMethodException,
			java.lang.reflect.InvocationTargetException,IllegalAccessException {
		String line = r.readLine();
		return new Identifier(line);
	}

	public boolean same(Object o) {
		o = Brackets.unbracket(o);
		return o instanceof Identifier && ((Identifier)o).string.equals(string);
	}

	public Component createView(FormulaView f) {
		return new IdentifierView(this);
	}
	
	public void saveLatex(java.io.BufferedWriter w) throws java.io.IOException {
		if (string.equals("")) return;
		if (string.length() == 1) w.write(string);
		else {
			w.write("\\mbox{");
			w.write(string);
			w.write("}");
		}
	}
}