/*
* ADOBE CONFIDENTIAL
*
* Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
*/

"use strict";

var fs = require("fs"),
    path = require("path"),
    _ = require("lodash");

var JSX_DIRECTORY = path.join(path.dirname(module.filename), "jsx");

// Cache for the template objects generated from the files.
var cache = {},
    _generator = null;

/**
 * @private
 * 
 * Initializes the JSXRunner with the generator instance.
 * JSXRunner cannot be used until initialization.
 * 
 * @param {object} generator
 */
function _init(generator) {
    _generator = generator;
}

/**
 * @private
 * 
 * Retrieve a JSX file from the jsx directory and convert it to a
 * lodash template. Also maintains a cache of previously loaded scripts.
 * 
 * @param {string} scriptName Name of script file (without the extension) to load
 * @return {function} lodash template function
 */
function _getJSXTemplate(scriptName) {
    if (cache[scriptName]) {
        return cache[scriptName];
    }

    var text = fs.readFileSync(path.join(JSX_DIRECTORY, scriptName + ".jsx")),
        template = _.template(text);

    cache[scriptName] = template;

    return template;
}

/**
 * Runs the JSX named script, merging the given data with the template
 * in the script file.
 * 
 * @param {string} scriptName Name of the JSX script (without the extension)
 * @param {object} data Data to merge into the template
 * @return {Promise} promise that is resolved the script has run.
 */
function runJSX(scriptName, data) {
    var template = _getJSXTemplate(scriptName),
        rendered = template(data);

    return _generator.evaluateJSXString(rendered);
}

exports._init = _init;
exports.runJSX = runJSX;
