/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2014 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.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true, node: true */
/*global _:true, csInterface:true, define: true, require: true, $: true, exports: true*/
"use strict";

//since it is basically just a text loader, we can use this to load jsx
var templateLoader = require("../TemplateLoader"),
    _   = require("underscore"),
    jsxPath = "../JSX/",
    fileExtension = ".jsx";


exports.getRawJSX = function (fileName) {
    var jsxFile,
        args = Array.prototype.slice.call(arguments, 1),
        jsxToRun;
    
    if (_.endsWith(fileName, fileExtension)) {
        fileName = fileName.replace(fileExtension, "");
    }
    
    if (typeof (args[args.length - 1]) === 'function') {
        args.pop();
    }
    
    jsxFile = templateLoader.loadTemplate(jsxPath + fileName + fileExtension);
    if (!jsxFile) {
        console.warn("No jsxfile found " + fileName);
        return "";
    }
    args.unshift(jsxFile);
    jsxToRun = _.sprintf.apply(_, args);
    return jsxToRun;
};

exports.runRawJSX = function (jsxToRun, callback) {
    if (csInterface) {
        csInterface.evalScript(jsxToRun, callback);
    }
};

exports.runJSX = function (action, rightNow) {
    
    var jsxToRun,
        args = Array.prototype.slice.call(arguments, 1),
        callback;
    
    if (typeof (args[args.length - 1]) === 'function') {
        callback = args.pop();
    } else {
        callback = function () {};
    }
    
    jsxToRun = exports.getRawJSX.apply(exports, arguments);
    
    if (rightNow) {
        exports.runRawJSX(jsxToRun, callback);
    } else {
        _.defer(function () { exports.runRawJSX(jsxToRun, callback); });
    }
};
