/*
  backgrid-button-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.ButtonCell = Backgrid.Cell.extend({
        template: null,
        className: 'button-cell',
        events: function () {
            return {
                'click .btn-cell-action': this.actionBtn_click,
            };
        },

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

            //Do not allow edition.
            this.column.set({ editable: false, });

            this.bindEvents();
        },
        render: function () {
            this.$el.html(this.template());

            this.$el.find('[data-toggle="tooltip"]').tooltip();

            this.checkMode();

            this.delegateEvents();

            return this;
        },
        bindEvents: function () {
            this.listenTo(this.model, 'change:isNew', this.checkMode);
        },

        checkMode: function () {
            var newRow = this.model.get('isNew');
            if (newRow) this.setNewRowMode(true);
            else this.setNewRowMode(false);
        },
        setNewRowMode: function (val) {
            var btnRemove = this.$el.find('.btn-remove');
            var btnSave = this.$el.find('.btn-save');
            var btnDiscard = this.$el.find('.btn-discard');

            if (val) {
                btnRemove.addClass('hide');
                btnSave.removeClass('hide');
                btnDiscard.removeClass('hide');
            } else {
                btnRemove.removeClass('hide');
                btnSave.addClass('hide');
                btnDiscard.addClass('hide');
            }
        },

        actionBtn_click: function (e) {
            try {
                var target = $(e.target);
                var actionData = target.closest('[data-cell-action]').data('cell-action');

                if (actionData)
                    this.model.trigger('backgrid:action', this.model, actionData);
            }
            catch (Error) { console.error(Error.stack); }
        },
    });
}));
