'use strict';

var q = require("q");
var SharedConstants = require('../../../shared/constants/SharedConstants');

function getTemplate(templateId, connectionName) {
    var deferred = q.defer();

    logger.debug("Getting template: " + templateId);
    var query = DBProvider.dataFindService.getFindTemplateQuery({documentId: templateId});

    var params = {};
    params.query = query;
    DBProvider.dataFindService.findOne(params, connectionName, function (queryErr, template) {
        if (queryErr) {
            var errorMsg = "Error getting document: " + queryErr;
            logger.error(errorMsg);
            deferred.reject(new Error(errorMsg));
        } else if (template) {
            deferred.resolve(template);
        } else {
            var errorMsg = "Error getting document: template not found: " + templateId;
            logger.error(errorMsg);
            deferred.reject(new Error(errorMsg));
        }
    });

    // don't check the permissions on getting the template.
    // The user may not have access to the template but the
    // template needs to be read to check the permissions
    return deferred.promise;
}


module.exports = {
    getTemplate: getTemplate
};
