var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
define(["require", "exports", "jquery", "jquery.cookie"], function (require, exports, jquery_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    jquery_1 = __importDefault(jquery_1);
    jquery_1.default.SATableActions = {
        defaults: {
            name: 'Group actions',
            clear: 'Clear selected',
            cookie: null,
            events: [],
            isDataTable: false,
            dom: {
                container: {
                    tag: 'div',
                    className: 'dt-buttons'
                },
                button: {
                    position: null
                }
            }
        }
    };
    jquery_1.default.extend(jquery_1.default.SATableActions.defaults, {
        name: 'Групові дії',
        clear: 'Очистити вибране'
    });
    if (jquery_1.default.fn.SATableActions == null) {
        jquery_1.default.fn.SATableActions = function (options) {
            options = options || {};
            if (typeof options === 'object') {
                this.each(function () {
                    //  var instanceOptions = $.extend(true, {}, options);
                    const instanceOptions = jquery_1.default.extend(jquery_1.default.SATableActions.defaults, {}, options);
                    SATableActions.create(this, instanceOptions);
                });
                return this;
            }
            else {
                throw new Error('Invalid arguments for SADImage: ' + options);
            }
        };
    }
    class SATableActions {
        static create(element, options) {
            return new SATableActions(element, options);
        }
        constructor(element, options) {
            this.$element = (0, jquery_1.default)(element);
            this.options = options;
            this.state = {
                items: [],
                checkboxAll: null,
                checkbox: [],
                button: null
            };
            if (!this.options.cookie) {
                throw new Error('cookie is required');
            }
            if (!this.options.events) {
                throw new Error('events is required');
            }
            /** @namespace $.fn.DataTable */
            if (jquery_1.default.fn.DataTable) {
                this.options.isDataTable = jquery_1.default.fn.DataTable.isDataTable(this.$element);
            }
            this._buildButton();
            if (!this.options.isDataTable) {
                this._buildAllCheckbox();
                this._buildCheckbox();
            }
            this._updateButton();
            this._handleEvents();
        }
        destroy() {
            this.state.button.remove();
            this.state.items = null;
            try {
                this.state.checkboxAll.remove();
            }
            catch (e) {
            }
            try {
                jquery_1.default.each(this.state.checkbox, (i, el) => {
                    (0, jquery_1.default)(el.item)
                        .remove();
                });
            }
            catch (e) {
            }
            // Container
            //  this.dom.container.remove();
            return this;
        }
        _buildButton() {
            /*  const buttonText = this.templateBtnContent(this.options.name, this.state.items.length);
            const button = $(this.templateButton(buttonText, this.options.events));
            this.container().append(button);
    
            this.state.button = this.container().find('button');*/
            this.state.clear = (0, jquery_1.default)(`<li><a href="#" class="text-bold">${this.options.clear}</a></li>`);
            (0, jquery_1.default)(this.options.dom.button.position)
                .append('<li class="divider"></li>');
            (0, jquery_1.default)(this.options.dom.button.position)
                .append(this.state.clear);
            this.state.actions = (0, jquery_1.default)(SATableActions.prototype.templateActions(this.options.events));
            (0, jquery_1.default)(this.options.dom.button.position)
                .append(this.state.actions);
        }
        _updateButton() {
            const items = this.state.items;
            /*  this.state.button.html(this.templateBtnContent(this.options.name, items.length));
            this.state.button.prop('disabled', items.length === 0);*/
            this.state.clear.toggleClass('hide', items.length === 0);
            this.state.actions.each(function () {
                (0, jquery_1.default)(this)
                    .toggleClass('disabled', items.length === 0);
                (0, jquery_1.default)(this)
                    .find('span')
                    .html(items.length > 0 ? ` (${items.length})` : '');
            });
        }
        _buildAllCheckbox() {
            let header;
            if (this.options.isDataTable) {
                const dataTableApi = this.$element.DataTable();
                header = (0, jquery_1.default)(dataTableApi.table()
                    .header());
            }
            else {
                header = this.$element.find('thead');
            }
            this.state.checkboxAll = (0, jquery_1.default)('<input type="checkbox" style="margin:0;vertical-align:middle"/>')
                .on('click', () => {
                this.$element.trigger('checkboxAllClick');
            });
            header.find('tr')
                .prepend((0, jquery_1.default)('<th />')
                .html(this.state.checkboxAll));
        }
        _buildCheckbox() {
            const instance = this;
            let rows;
            if (this.options.isDataTable) {
                const dataTableApi = this.$element.DataTable();
                rows = (0, jquery_1.default)(dataTableApi.rows()
                    .nodes());
            }
            else {
                rows = this.options.container.find('tbody')
                    .find('tr');
            }
            this.state.checkbox = [];
            rows.each(function () {
                const code = (0, jquery_1.default)(this)
                    .attr('data-code');
                const item = (0, jquery_1.default)('<input type="checkbox" style="margin:0;vertical-align:middle"/>')
                    .on('click', function () {
                    instance.$element.trigger('checkboxClick', {
                        self: this,
                        code: code
                    });
                });
                instance.state.checkbox.push({
                    code: code,
                    item: item
                });
                (0, jquery_1.default)(this)
                    .prepend((0, jquery_1.default)('<td class="SA-TableAction-checkbox"/>')
                    .html(item));
            });
            this.$element.trigger('drawCheckbox');
        }
        _handleEvents() {
            if (this.options.isDataTable) {
                const dataTableApi = this.$element.DataTable();
                dataTableApi.on('init', () => {
                    this._buildAllCheckbox();
                });
                dataTableApi.on('draw', () => {
                    this._buildCheckbox();
                    if (this.state.checkboxAll) {
                        this.state.checkboxAll.prop('checked', false);
                    }
                });
                dataTableApi.on('destroy', () => {
                    this.destroy();
                });
            }
            this.state.clear.on('click', (ev) => {
                ev.preventDefault();
                this.state.items = [];
                this.$element.trigger('checkboxChange');
                jquery_1.default.each(this.state.checkbox, (i, el) => {
                    (0, jquery_1.default)(el.item)
                        .prop('checked', false);
                });
            });
            this.$element.on('checkboxAllClick', () => {
                //  console.log('event.checkboxAllClick');
                const select = this.state.checkboxAll.is(':checked');
                jquery_1.default.each(this.state.checkbox, (i, el) => {
                    (0, jquery_1.default)(el.item)
                        .prop('checked', select);
                    if (select) {
                        if (this.state.items.indexOf(el.code) < 0) {
                            this.state.items.push(el.code);
                        }
                    }
                    else {
                        this.state.items.splice(this.state.items.indexOf(el.code), 1);
                    }
                });
                this.$element.trigger('checkboxChange');
            });
            this.$element.on('checkboxClick', (eventObject, props) => {
                if ((0, jquery_1.default)(props.self)
                    .is(':checked')) {
                    this.state.items.push(props.code);
                }
                else {
                    this.state.items.splice(this.state.items.indexOf(props.code), 1);
                    this.state.checkboxAll.prop('checked', false);
                }
                this.$element.trigger('checkboxChange');
            });
            this.$element.on('checkboxChange', () => {
                jquery_1.default.cookie(this.options.cookie, this.state.items.join('.'));
                this._updateButton();
            });
            this.$element.on('drawCheckbox', () => {
                //  console.log('event.drawCheckbox');
                const items = jquery_1.default.cookie(this.options.cookie);
                if (items) {
                    let list;
                    if (items.indexOf(',') > 0) {
                        list = items.split(',');
                    }
                    else {
                        list = items.split('.');
                    }
                    jquery_1.default.each(list, (i, a) => {
                        if (this.state.items.indexOf(a) < 0) {
                            this.state.items.push(a);
                        }
                    });
                    jquery_1.default.each(this.state.checkbox, (i, el) => {
                        if (list.indexOf(el.code) > -1) {
                            (0, jquery_1.default)(el.item)
                                .prop('checked', true);
                        }
                    });
                    this._updateButton();
                }
            });
        }
    }
    SATableActions.prototype.templateBtnContent = (name, items) => {
        return name + (items > 0 ? (' (' + items + ')') : '') + '<span class="caret"></span>';
    };
    SATableActions.prototype.templateActions = (actions) => {
        let html = '';
        jquery_1.default.each(actions, (i, el) => {
            html += '<li><a href="' + el.link + '">' + el.title + '<span></span></a></li>';
        });
        return html;
    };
    SATableActions.prototype.templateButton = (title, actions) => {
        let html = '';
        html += '<div class="dropdown">';
        html += '<button class="btn btn-default dt-button dropdown-toggle" disabled type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">';
        html += title;
        html += '</button>';
        html += '<ul class="dropdown-menu pull-right">';
        jquery_1.default.each(actions, (i, el) => {
            html += '<li><a href="' + el.link + '">' + el.title + '</a></li>';
        });
        html += '</ul>';
        html += '</div>';
        return html;
    };
});
