package gve.calc.formula;

import java.util.Hashtable;
import java.awt.*;

public abstract class PrefixUnaryOp extends UnaryOp {
	public PrefixUnaryOp() {
		super();
	}

	public PrefixUnaryOp(Part ch) {
		super(ch);
	}

	public UnaryOp getInstance(Part ch) {
		return getInstance(getName(),ch);
	}

	//----------static stuff----------
	private static Hashtable repository = new Hashtable();

	public static void registerFactory(String name,UnaryOpFactory factory) {
		repository.put(name,factory);
	}

	public static UnaryOp getInstance(String name,Part ch) {
		UnaryOpFactory fact = (UnaryOpFactory)repository.get(name);
		if (fact == null)
			throw new Error("No factory for "+name);
		return fact.createUnaryOp(name,ch);
	}

	public static boolean isOperatorName(String name) {
		return repository.containsKey(name);
	}

	public static String operatorPrefix(String name) {
		return InfixBinaryOp.operatorPrefix(name,repository);
	}

	//----------instance stuff----------

	public boolean simpleRotate(Formula f,FormulaView view) {
		if (getParent() instanceof InfixBinaryOp) {
			InfixBinaryOp par = (InfixBinaryOp)parent;
			// Rotate myself upwards: (Parg) I ... -> P(arg I ...)
			if (this==par.left && getPri()<par.getLeftPri()) {
				Part cursorpart = null;
				if (view != null) cursorpart = view.getCursorPart();
				Identifier dummy = new Identifier();
				int cpos = 0;
				HasCursorPos restoreCursorComp = null;
				if (cursorpart == this) {	// Record cursor position
					Component ccomp = view.getCursorComp();
					if (ccomp instanceof HasCursorPos) {
						restoreCursorComp = (HasCursorPos)ccomp;
						cpos = restoreCursorComp.getCursorPos();
					}
				}
				f.replace(this,dummy);
				f.replace(par,this);
				Part oldchild = child;
				f.replace(child,par);
				f.replace(dummy,oldchild);
				if (restoreCursorComp != null) {
					view.setCursorComp((Component)restoreCursorComp,cpos);
				}
				return true;
			}
		}
		return false;
	}

	Identifier dismantle(String str,Formula f) {
		Identifier result = new Identifier(str);
		f.replace(this,new OperatorSpace(result,child));
		return result;
	}

	public Component createView(FormulaView view) {
		return new PrefixUnaryOpView(this,view);
	}

	
A default strategy, so a subclass only has to implement saveOperatorLatex()
public void saveLatex(java.io.BufferedWriter w) throws java.io.IOException { saveOperatorLatex(w); w.write(" "); child.saveLatex(w); } public void saveOperatorLatex(java.io.BufferedWriter w) throws java.io.IOException { w.write(getName()); } }