package gve.calc.formula;

import java.awt.*;

public class StaticStringView extends CursorPosLabel implements View,KeydnListener,MouseSensitive {
	private StaticString model;

	public StaticStringView(StaticString model,FormulaView view) {
		super(model.getName());
		this.model = model;
	}

	public Object getModel() { return model; }

	public void updateView(Object with) {}

	public boolean mousePressed(int flags,int x,int y) { return false; }

	// almost same as IdentifierView.mouseDown
	public void mouseDown(int flags,int x,int y) {
		FontMetrics fm = getFontMetrics(getFont());
		String string = model.getName();
		int len = string.length();
		FormulaView view = FormulaView.get(this);
		for (int i = 0; i < len; i++) {
			int w = fm.charWidth(string.charAt(i));
			if (x < w/2) {
				view.setCursorComp(this,i);
				return;
			}
			x -= w;	// advance one letter to the right
		}
		// Place cursor at the rightmost position
		view.setCursorComp(this,len);
	}

	public boolean keydn(int key) {
		switch (key) {
		case Key_LEFT:
			if (getCursorPos() > 0) {
				setCursorPos(getCursorPos() - 1);
				return true;
			}
			return false;
		case Key_RIGHT:
			if (getCursorPos() < model.getName().length()) {
				setCursorPos(getCursorPos() + 1);
				return true;
			}
			return false;
		default:
			if (key == Key_BS) ;	// backspace
			else if (key < 32) return false;
			Identifier ident = new Identifier(model.getName());
			{	FormulaView view = FormulaView.get(this);
				int cp = getCursorPos();
				view.getFormula().replace(model,ident);
				Component identView = view.getView(ident);
				if (cp >= 0) view.setCursorComp(identView,cp);
				return ((KeydnListener)identView).keydn(key);
			}
		}
	}
}