package gve.calc.formula;

import java.awt.*;

public class PostfixUnaryOpView extends HasBaselineContainer implements HasCursorPos,KeydnListener,View {
	private PostfixUnaryOp model;

	public PostfixUnaryOpView(PostfixUnaryOp model,FormulaView view) {
		this (model,view,new CursorPosLabel(model.getName()));
	}

	public PostfixUnaryOpView(PostfixUnaryOp model,FormulaView view,Component operatorView) {
		this.model = model;
		add(view.getView(model.child));
		add(operatorView);
		setLayout(new HorizontalLayoutMgr());
	}

	public void updateView(Object with) {
		System.out.println("PrefixUnaryOpView.updateView() error");
	}

	public Object getModel() { return model; }

	public void setCursorPos(int pos) {
		switch (pos) {
		case Somewhere_LEFT:
			FormulaView.get(this).setCursorPart(model.child,Somewhere_LEFT);
			break;
		case Somewhere_MYRIGHT:
		case Somewhere_RIGHT:
			getOperatorView().setCursorPos(Somewhere_RIGHT);
			break;
		case Somewhere_MYLEFT:
			getOperatorView().setCursorPos(Somewhere_LEFT);
			break;
		default:
			getOperatorView().setCursorPos(Somewhere);
		}
	}

	public int getCursorPos() {
		FormulaView view = FormulaView.get(this);
		Part cursorpart = view.getCursorPart();
		if (Part.isDescendantOr(cursorpart,model.child))
			return Somewhere_LEFT;
		if (cursorpart == model)
			return getOperatorView().getCursorPos();
		return Somewhere;
	}

	public void activate() {}

	public void deactivate() {
		// While dismantling etc., left or right child could
		// already be removed. In that case, do nothing
		if (getComponentCount() == 2)
			getOperatorView().deactivate();
	}

	HasCursorPos getOperatorView() {
		return (HasCursorPos)getComponent(1);
	}

	public boolean keydn(int key) {
		FormulaView fview = FormulaView.get(this);
		HasCursorPos opView = getOperatorView();
		int cp = opView.getCursorPos();
		if (key == Key_LEFT) {
			if (cp > 0) {
				opView.setCursorPos(cp - 1);
				return true;
			} else if (cp == 0) {
				fview.setCursorPart(model.child,Somewhere_RIGHT);
				return true;
			}
			return false;
		} else if (key == Key_RIGHT) {
			if (cp >= 0) {
				if (cp>=0 && cp < model.getName().length()) {
					opView.setCursorPos(cp + 1);
					return true;
				}
			} else if (Part.isDescendantOr(fview.getCursorPart(),model.child)) {
				// Cannot go more to the right in a (sub)child on the left side
				// so move to the middle
				fview.setCursorComp(this);
				opView.setCursorPos(0);
				return true;
			}
			return false;
		}
		return OperatorController.keydn(key,this);
	}
}