/*
 * 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.
 */

/*global  $*/
"use strict";

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

var Strings     = require("./LocStrings");

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) {
    var result = Q.defer();

    loadTemplate(name).then(
        function (template) {
            result.resolve($(template(_.extend({
                    Strings: Strings
            }, params || {}))));
        },
        function(err) {
            result.reject(err);
        }
    );

    return result.promise;
}


exports.renderTemplate = renderTemplate;
