(function(paw){
    function IdentSearchTable(settings) {
        var self = this;
        this.settings = settings; // { url, tableSelector, columns }
        this.datatable = null;
        this.data = [];
        this.selection = [];
        this.isInit = false;
        this.suppressRequest = false;

        this.handleRowSelection = function () {
            var $row = $(this);
            self.selectEntity(paw.utils.value.strToNum($row.attr('data-entity-id')));
        }
    }
    
    IdentSearchTable.prototype.init = function(){
        return this.initDatagrid();
    };

    IdentSearchTable.prototype.destroy = function () {
        $('.ident-search-popup ' + this.settings.tableSelector).off('click', 'tr', this.handleRowSelection);
        this.datatable.destroy();
        this.datatable = null;
        this.data = [];
        this.selection = [];

        $(this.settings.tableSelector + ' input[type=checkbox][data-ident-search-selection]').off('change');
        return this; // for chaining
    };

    IdentSearchTable.prototype.reload = function(){
        $(this.settings.tableSelector + ' input[type=checkbox][data-ident-search-selection]').off('change');
        this.datatable.ajax.reload();
        return this; // for chaining
    };

    IdentSearchTable.prototype.resetScrollTop = function () {
        $(this.datatable.table().node()).parent().scrollTop(0);
        return this; // for chaining
    };
    
    IdentSearchTable.prototype.initDatagrid = function(){
        var self = this;
        var d = paw.utils.async.defer();
        var $table = $('.ident-search-popup ' + this.settings.tableSelector);
        this.datatable = $table.DataTable({
            responsive: false,
            // override ajax because we need to support "data clear" behavior - which when re-rendering grid
            // also executes API call
            ajax: function (data, callback, settings) {
                if (data.length === 0) {
                    data.length = 10;
                }
                if (self.suppressRequest) {
                    callback({ data: [] });
                    self.suppressRequest = false;
                } else {
                    $.ajax({
                        url: self.settings.url,
                        method: 'POST',
                        data: self.request({
                            draw: data.draw,
                            start: data.start,
                            length: data.length
                        }),
                        success: function (response) {
                            callback(response);
                        },
                        error: function () {
                            console.error("AJAX Error:", error);
                            self.isInit = true;
                            d.reject();
                            callback({ data: [] });
                        }
                    });
                }
            },
            stateSave: false,
            stateSaveCallback: undefined,
            stateLoadCallback: undefined,
            fixedHeader: true,
            scrollX: true,
            scrollY: $('.tables-holder').height() + 'px',
            scrollCollapse: true,
            scroller: {
                rowHeight: 'auto',
                displayBuffer: 0.5,
                loadingIndicator: true
            },
            colReorder: false,
            columns: this.settings.columns,
            createdRow: function (row, data, dataIndex) {
                var $row = $(row);
                $row.attr('data-entity-id', data.Id);

                if(paw.utils.value.isFunction(self.onRowRendered)){
                    self.onRowRendered($row, data, dataIndex);
                }
            },
            initComplete: function(){
                self.isInit = true;
                d.resolve(self.data);
            }
        }).on('xhr.dt', function (e, settings, json, xhr) {
            if (json) {
                self.data = json.data;
            }
            if(paw.utils.value.isFunction(self.onDataLoaded)){
                self.onDataLoaded(self.data);
            }
            
            return json;
        }).on('draw.dt', function () {
            if(paw.utils.value.isFunction(self.onRendered)){
                self.onRendered(self.data);
            }
        });
        $table.on('click', 'tr', this.handleRowSelection);
        return d.promise;
    };

    IdentSearchTable.prototype.clearData = function () {
        this.suppressRequest = true;
        this.data = [];
        this.datatable.clear().draw();
    };

    IdentSearchTable.prototype.selectEntity = function(entityId){
        var self = this;
        if (this.selection.length > 0) {
            if (paw.utils.value.notSet(this.selection[0])) {
                paw.utils.value.deleteItem(self.selection, function (item, i) {
                    return i === 0;
                });
            }
            else {
                var selectionId = this.selection[0].Id;
                this.getEntityRow(selectionId).removeClass('ident-search-row-selected');
                paw.utils.value.deleteItem(self.selection, function (item, i) {
                    return i === 0;
                });
            }
        }

        var $row = this.getEntityRow(entityId);

        $row.addClass('ident-search-row-selected');
        var entity = paw.utils.value.get(this.data, function (item) {
            return item.Id === entityId;
        });
        this.selection.push(entity);

        if (paw.utils.value.isFunction(this.onEntitySelected)) {
            this.onEntitySelected(entity);
        }
        return this; // for chaining
    };

    IdentSearchTable.prototype.getEntityRow = function (entityId) {
        return $('.ident-search-popup ' + this.settings.tableSelector + ' tr[data-entity-id="' + entityId + '"]');
    };

    paw.com.identSearch.IdentSearchTable = IdentSearchTable;
})(paw);