package gve.calc.formula;

public class OperatorAssign extends InfixBinaryOp {
	private byte kind;

	public static final byte UNION = 0;
	public static final byte ASSIGN = 1;
	public static final byte PLUS = 2;

	private static String [] names = { "union=",":=","+=" };

	public OperatorAssign(String name,Part l,Part r) {
		super(l,r);
		for (int i = names.length-1; i>=0; i--) {
			if (names[i].equals(name)) {
				kind = (byte)i;
				break;
			}
		}
	}

	public String getName() { return names[kind]; }
	public int getPri() { return 600; }
	public int getLeftPri() { return 610; }
	public int getRightPri() { return 590; }

	public Part evaluate(Evaluator ev) {
		Part righthand = right.evaluate(ev);
		switch (kind) {
		case UNION:
			// PENDING: this code doesn't seem to work.
			if (left instanceof Identifier) {
				String name = ((Identifier)left).getString();
				if (!(right instanceof Brackets)) {
					System.out.println("rhs no set");
					return null;
				}
				Brackets rhs = (Brackets)right;
				if (rhs.getKind() != Brackets.CURLY) {
					System.out.println("rhs no set");
					return null;
				}
				Part lhs = ev.getValue(name);
				if (!(lhs instanceof Brackets)) {
					System.out.println("lhs no set");
					return null;
				}
				if (((Brackets)lhs).getKind() != Brackets.CURLY) {
					System.out.println("lhs no set");
					return null;
				}
				Part rd = rhs.child;
				Part newval = (Part)((Brackets)lhs).child.clone();
				while (true) {
					if (rd instanceof OperatorComma) {
						OperatorComma comma = (OperatorComma)rd;
						if (!OperatorComma.listContains(newval,comma.left)) {
							newval = new OperatorComma((Part)comma.left.clone(),newval);
						}
						rd = comma.right;
						continue;
					}
					if (!OperatorComma.listContains(newval,rd))
						newval = new OperatorComma((Part)rd.clone(),newval);
					break;
				}
				ev.setValue(name,newval);
			} else System.out.println("Can't union= with lhs "+left);
			break;
		case ASSIGN:
			if (left instanceof Identifier) {
				String name = ((Identifier)left).getString();
				Part newval = (Part)righthand.clone();
				ev.setValue(name,newval);
				return (Part)righthand.clone();
			} else System.out.println("can't assign to "+left);
			break;
		case PLUS:
			break;
		}
		return null;
	}
}