// Generated by CoffeeScript 1.11.1
(function() {
  var Adapter, Handlebars, W, clone, fs, merge, path,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  Adapter = require('../../adapter_base');

  clone = require('lodash.clone');

  merge = require('lodash.merge');

  path = require('path');

  fs = require('fs');

  W = require('when');

  Handlebars = (function(superClass) {
    var compile, register_helpers;

    extend(Handlebars, superClass);

    function Handlebars() {
      return Handlebars.__super__.constructor.apply(this, arguments);
    }

    Handlebars.prototype.name = 'handlebars';

    Handlebars.prototype.extensions = ['hbs', 'handlebars'];

    Handlebars.prototype.output = 'html';

    Handlebars.prototype._render = function(str, options) {
      var compiler;
      compiler = clone(this.engine);
      register_helpers(compiler, options);
      return compile((function(_this) {
        return function() {
          return compiler.compile(str)(options);
        };
      })(this));
    };

    Handlebars.prototype._compile = function(str, options) {
      var compiler;
      compiler = clone(this.engine);
      register_helpers(compiler, options);
      return compile((function(_this) {
        return function() {
          return compiler.compile(str);
        };
      })(this));
    };

    Handlebars.prototype._compileClient = function(str, options) {
      var compiler;
      compiler = clone(this.engine);
      register_helpers(compiler, options);
      return compile((function(_this) {
        return function() {
          return "Handlebars.template(" + (compiler.precompile(str)) + ");";
        };
      })(this));
    };

    Handlebars.prototype.clientHelpers = function() {
      var runtime_path;
      runtime_path = path.join(this.engine.__accord_path, 'dist/handlebars.runtime.min.js');
      return fs.readFileSync(runtime_path, 'utf8');
    };


    /**
     * @private
     */

    register_helpers = function(compiler, opts) {
      if (opts.helpers) {
        compiler.helpers = merge(compiler.helpers, opts.helpers);
      }
      if (opts.partials) {
        return compiler.partials = merge(compiler.partials, opts.partials);
      }
    };

    compile = function(fn) {
      var err, res;
      try {
        res = fn();
      } catch (error) {
        err = error;
        return W.reject(err);
      }
      return W.resolve({
        result: res
      });
    };

    return Handlebars;

  })(Adapter);

  module.exports = Handlebars;

}).call(this);
