package com.google.sitebricks.compiler;

import com.google.sitebricks.Evaluator;
import net.jcip.annotations.Immutable;

/**
 * Created with IntelliJ IDEA.
 * On: 20/03/2007
 *
 * A simple wrapper around a string or expression (with evaluator), denoting it as a
 *  renderable token.
 *
 * @author Dhanji R. Prasanna (dhanji at gmail com)
 * @since 1.0
 */
@Immutable
class CompiledToken implements Token {
    private final String token;
    private final boolean isExpression;
    private final Evaluator evaluator;

    private CompiledToken(String token, boolean expression) {
        this.token = token;
        this.evaluator = null;
        isExpression = expression;
    }

    private CompiledToken(Evaluator evaluator, boolean expression) {
        this.evaluator = evaluator;
        isExpression = expression;
        this.token = null;
    }

    public boolean isExpression() {
        return isExpression;
    }

    public Object render(Object bound) {
        return isExpression ? evaluator.evaluate(null, bound) : token;
    }

    //local factories
    static CompiledToken expression(String token, EvaluatorCompiler compiler) throws ExpressionCompileException {
        //strip leading ${ and trailing }
        return new CompiledToken(compiler.compile(token.substring(2, token.length() - 1)), true);
    }

    static CompiledToken text(String token) {
        return new CompiledToken(token, false);
    }
}

@@ -36,16 +36,52 @@
 ler;%0D%0A%0D%0A
+import org.mvel2.DataConversion;%0D%0A%0D%0A
 import c
@@ -1005,22 +1005,22 @@
  public 
-Object
+String
  render(
@@ -1036,39 +1036,36 @@
 und) %7B%0D%0A        
-return 
+if (
 isExpression ? e
@@ -1064,10 +1064,37 @@
 sion
- ?
+) %7B%0D%0A        %09Object object =
  eva
@@ -1125,17 +1125,253 @@
 und)
- : token;
+;%0D%0A        %09if (object instanceof String) %7B%0D%0A        %09%09return (String) object;%0D%0A        %09%7D%0D%0A        %09else %7B%0D%0A        %09%09return DataConversion.convert(object, String.class);%0D%0A        %09%7D%0D%0A        %7D%0D%0A        else %7B%0D%0A        %09return token;%0D%0A        %7D
 %0D%0A  

Convert expression results to String using DataConversion