package com.jfireel.expression.node.impl;

import com.jfireel.expression.token.Operator;
import com.jfireel.expression.util.number.PlusUtil;

import java.util.Map;

public class PlusNode extends OperatorResultNode {
	private static final ThreadLocal<StringBuilder> LOCAL = new ThreadLocal<StringBuilder>() {
		protected StringBuilder initialValue() {
			return new StringBuilder();
		}

		;
	};

	public PlusNode() {
		super(Operator.PLUS);
	}

	@Override
	public Object calculate(Map<String, Object> variables) {
		Object leftValue = leftOperand.calculate(variables);
		Object rightValue = rightOperand.calculate(variables);
		if (leftValue instanceof String || rightValue instanceof String) {
			StringBuilder cache = LOCAL.get();
			if(leftValue != null) {
				cache.append(leftValue);
			}
			if(rightValue != null) {
				cache.append(rightValue);
			}
			String result = cache.toString();
			cache.setLength(0);
			return result;
		} else {
			if (leftValue != null && rightValue != null) {
				return PlusUtil.calculate((Number) leftValue, (Number) rightValue);
			}else if (leftValue == null && rightValue != null) {
				return  rightValue;
			}else if  (leftValue != null && rightValue == null) {
				return  leftValue;
			}
		}
		return null;
	}
}
