/*
 * 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 Handlebars  = require("handlebars"),
    fs          = require("fs"),
    path        = require("path"),
    Q           = require("Q"),
    _           = require("lodash"),
    Strings     = require("./LocStrings"),
    PreviewGlobal = require("../../common/PreviewGlobal");

var templates = {
};


function readTemplate(name) {
    var result = Q.defer(),
        filename = path.resolve(path.dirname(module.filename), "../html/" + name + ".html");

    fs.readFile(filename, function(err, data) {
        if (!err) {
            result.resolve(Handlebars.compile(data.toString()));
        } else {
            result.reject(err);
        }
    });

    return result.promise;
}

function loadTemplate(name) {
    var result = Q.defer();

    if (templates[name]) {
        result.resolve(templates[name]);
    } else {
        readTemplate(name).then(
            function(template) {
                templates[name] = template;
                result.resolve(template);
            },
            function(err) {
                result.reject(err);
            }
        );
    }

    return result.promise;
}

function renderTemplate(name, params) {
    return loadTemplate(name).then(
        function (template) {
            return PreviewGlobal.window.$(template(_.extend({
                    Strings: Strings
                }, params || {})));
        }
    );
}


exports.renderTemplate = renderTemplate;
