/*
  backgrid-valid-limit-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._;

    function MakeCellValidLimit(cellView) {
        return cellView.extend({
            className: cellView.prototype.className + ' valid-limit-cell',
            invalidMessage: 'Invalid value',
            validLimitProp: null,

            initialize: function () {
                cellView.prototype.initialize.apply(this, arguments);

                this.listenTo(this.model, 'change:' + this.validLimitProp, this.model_change_validLimitProp);
            },
            render: function () {
                cellView.prototype.render.apply(this, arguments);

                this.update();

                return this;
            },
            update: function () {
                var value = this.model.get(this.column.get('name')),
                    limit = this.model.get(this.validLimitProp);

                if (this.validate(value, limit) == true) {
                    this.$el.attr('title', '')
                            .removeClass('invalid');
                }
                else {
                    var invMsg = ($.isFunction(this.invalidMessage) == true)
                                    ? this.invalidMessage(value, limit)
                                    : this.invalidMessage;

                    this.$el.attr('title', invMsg)
                            .addClass('invalid');
                }
            },
            validate: function (value, limit) {
                return (value <= limit);
            },

            model_change_validLimitProp: function (model, value, opt) {
                try {
                    this.update();
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); };
            },
        });
    };

    Backgrid.Extension.MakeCellValidLimit = MakeCellValidLimit;
}));
