// first get a reference to the `dust` instance
var dust = require('dustjs-linkedin');

/*
* Evaluate maths
* Usage:
* ```
* {@maths eval="{a}+{b}+{c}" /}
* ```
* Or in the block format:
* ```
* {@maths eval="{a}+{b}+{c}"}
*   {result}
* {/maths}
* ```
*/

dust.helpers.maths = function( chunk, context, bodies, params ){
	console.log("SHOULD CALL");
    try {
        var isMalformed;
        var resolved = context.resolve(params.eval);
        var equation = resolved.replace(/([\d\.]+)([*/%+-])/gm, function(origin, number, operator) {
            if (!isNaN(number) && operator) {
                return Number(number) + operator;
            } else {
                isMalformed = true;
            }
        }.bind(this));

        if (!isMalformed && bodies.block) {
            return chunk.render(bodies.block, context.push({
                result: eval(equation)
            }));
        } else {
            return chunk.write(resolved);
        }
    } catch (e) {
      return chunk.write(e);
         //chunk.end();
    }
};
