/*
  backgrid-calendar-cell 1.0.0
*/
(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    // AMD
    define(["underscore", "backgrid"], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory(require("underscore"), require("backgrid"));
  } else {
    // Browser globals
    factory(root._, root.Backgrid);
  }

}(this, function (_, Backgrid) {

    //Fix require config issue with Underscore.
    if (!_)
        _ = this._;

    Backgrid.Extension.ComputedCell = Backgrid.StringCell.extend({
        super: null,
        calculate: null, //Function
        className: 'computed-cell',
        deps: null, //Array of string with model attributes to be used.
        constructor: function () {
            this.super = Backgrid.Extension.ComputedCell.__super__;

            this.super.constructor.apply(this, arguments);

            var that = this;

            _.each(this.deps, function (item) {
                that.listenTo(that.model, 'change:' + item, that._model_change_dep);
            });
        },
        render: function () {
            if (this.calculate) {
                var value = this.calculate.apply(this, _.map(this.deps, this.model.get, this.model));

                this.$el.html(value);
            }

            this.delegateEvents();

            return this;
        },
        _model_change_dep: function (model, opt) {
            try {
                this.render();
            }
            catch (Error) { console.error(Error); }
        }
    });
}));
