import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormGroup } from '@angular/forms';
export var TableComponent = (function () {
    function TableComponent() {
        this.action = new EventEmitter(true);
        this.EOL = '\r\n';
        this.BOM = '\ufeff';
        this.DEFAULT_FIELD_SEPARATOR = ';';
        this.form = new FormGroup({});
        this.filtersModel = {};
        this.filters = [];
    }
    Object.defineProperty(TableComponent.prototype, "items", {
        get: function () {
            return this._items;
        },
        set: function (items) {
            this.displayedItems = items;
            this._items = items;
        },
        enumerable: true,
        configurable: true
    });
    TableComponent.prototype.getValue = function (item, fieldId, fn) {
        var value = item;
        if (fieldId) {
            var split = fieldId.split('.');
            split.forEach(function (v) {
                if (value)
                    value = value[v];
            });
            return fn ? fn(value) : value;
        }
        return '';
    };
    // ngOnInit(): void {
    //   // this.displayedItems = this.items
    // }
    // ngOnChanges(changes: SimpleChanges): void {
    //   this.displayedItems = changes['items'].currentValue
    // }
    TableComponent.prototype.ngAfterViewInit = function () {
        var _this = this;
        if (this.options.filters) {
            this.options.filters.forEach(function (filter) {
                if (filter.type === 'select' && !filter.options)
                    filter.options = _this.items;
                filter.control.valueChanges.subscribe(function (value) {
                    _this.updateFilters(filter.id, value);
                });
            });
        }
    };
    TableComponent.prototype.updateFilters = function (filter, values) {
        this.filters[filter] = values;
        this.search();
    };
    TableComponent.prototype.search = function () {
        var _this = this;
        this.displayedItems = this.items.filter(function (data) {
            /*FILTERS*/
            if (_this.options.filters)
                for (var i in _this.filters) {
                    if (!data[i])
                        return false;
                    if (!(new RegExp('(' + _this.filters[i] + ')', 'i').test(data[i].toString()) || !_this.filters[i] || _this.filters[i].toString() === ''))
                        return false;
                }
            /*FULL TEXT*/
            if (_this.options.fulltext && _this.keyword && _this.keyword !== '') {
                // _this.fields.forEach(function (field) {
                for (var j in _this.options.fulltext) {
                    if (new RegExp('(' + _this.keyword + ')', 'i').test(_this.getValue(data, _this.options.fulltext[j].field, _this.options.fulltext[j].fn)))
                        return true;
                }
                return false;
            }
            return true;
        });
    };
    TableComponent.prototype.onAction = function (index, type, item, subItem) {
        if (item === void 0) { item = null; }
        if (subItem === void 0) { subItem = null; }
        this.action.next({
            index: index,
            type: type,
            item: item,
            subItem: subItem
        });
    };
    TableComponent.prototype.showWithConditions = function (action, item) {
        var _this = this;
        var good = true;
        if (action.conditions) {
            action.conditions.forEach(function (cond) {
                if (cond.conditionValue && _this.getValue(item, cond.condition) !== cond.conditionValue)
                    good = false;
                if (cond.nConditionValue && _this.getValue(item, cond.condition) === cond.nConditionValue)
                    good = false;
            });
        }
        return good;
    };
    TableComponent.prototype.exportToCSV = function () {
        var csv;
        csv = this.getCSVHeaders() + this.EOL;
        csv += this.getCSVBody();
        if (csv === '') {
            console.log('Invalid data');
            return;
        }
        // Read blob.
        var blob = new Blob([csv], { type: 'text/csv;charset=UTF-8' });
        var url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        document.body.appendChild(a);
        // a.style = 'display: none';
        a.href = url;
        a.download = this.options.csv.title.replace(/ /g, '_') + '.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    };
    /**
     * Create Headers
     */
    TableComponent.prototype.getCSVHeaders = function () {
        var row = [];
        this.fields.forEach(function (field) {
            if (!field.actions)
                row.push(field.field);
        });
        return row.join(this.DEFAULT_FIELD_SEPARATOR);
    };
    /**
     * Create Body
     */
    TableComponent.prototype.getCSVBody = function () {
        var _this = this;
        var rows = [];
        this.items.forEach(function (item) {
            var row = [];
            _this.fields.forEach(function (field) {
                if (!field.actions)
                    row.push('"' + _this.getValue(item, field.field, field.fn) + '"');
            });
            rows.push(row.join(_this.DEFAULT_FIELD_SEPARATOR));
        });
        return rows.join(this.EOL);
    };
    TableComponent.decorators = [
        { type: Component, args: [{
                    selector: 'tw-table',
                    template: "\n    <div class=\"card\">\n      <div class=\"card-header\">\n        <strong *ngIf='options.title' >{{options.title}}</strong>\n        <button *ngIf='options.create' class='btn btn-success pull-right' (click)='onAction(null, \"create\")'><i class='fa fa-plus'> {{options.create.label}}</i></button>\n      </div>\n      <div class=\"card-block scroll-x\">\n      <strong *ngIf='options.filters' >Filtres</strong>\n      <tw-reactive-form *ngIf='options.filters' [fields]='options.filters' [form]='form' [request]='filtersModel'></tw-reactive-form>\n        <table class=\"table table-striped table-bordered tickets-list table-responsive\" [mfData]=\"displayedItems\" #mf=\"mfDataTable\" [mfRowsOnPage]=\"options.rows || 20\">\n          <thead>\n            <tr>\n              <th *ngFor='let field of fields'>\n                <mfDefaultSorter by=\"{{field.field}}\" *ngIf='field.field'>{{field.label || field.field}}</mfDefaultSorter>\n              </th>\n            </tr>\n          </thead>\n          <tbody>\n            <tr *ngFor=\"let item of mf.data;let i = index\">\n              <td *ngFor='let field of fields' [ngClass]=\"field.class\">\n                <span *ngIf='field.tag' class=\"tag tag-info\" [ngClass]=\"getValue(item, field.field, field.fn)\">{{getValue(item, field.field, field.fn)}}</span>\n                <span *ngIf='field.boolean' class=\"tag\" [ngClass]=\"getValue(item, field.field, field.fn) ? 'tag-success' : 'tag-danger'\"><i class='fa' [ngClass]=\"getValue(item, field.field, field.fn) ? 'fa-thumbs-up' : 'fa-thumbs-down'\"></i></span>\n                <span *ngIf='field.text'>{{getValue(item, field.field, field.fn) | twDash}}</span>\n\n                <div *ngFor='let action of field.actions'>\n                  <button *ngIf='action.type===\"button\" && showWithConditions(action, item)' class='btn btn-{{action.class}} btn-sm'\n                    (click)='onAction(i, action.action, item)'><i class=\"fa fa-{{action.icon}}\"></i> \n                    {{action.text}}\n                    </button>\n                  <span *ngIf='action.type===\"text\"  && showWithConditions(action, item)'>\n                    {{action.text}}\n                    </span>\n                </div>\n                <div *ngIf='field.list'>\n                  <span *ngFor='let l of item[field.list];let j = index' (click)='onAction(j, field.action, item, l)' [ngClass]='l[field.classAttr]'\n                    class='{{field.classLi}}'></span>\n                </div>\n              </td>\n            </tr>\n          </tbody>\n          <tfoot>\n            <tr>\n              <td colspan=\"6\">\n                <mfBootstrapPaginator [rowsOnPageSet]=\"[5,10,25]\"></mfBootstrapPaginator>\n              </td>\n            </tr>\n          </tfoot>\n        </table>\n      </div>\n      <div class='card-footer'>\n            <button *ngIf='options.csv' class='btn btn-primary ' (click)='exportToCSV()'><i class='fa fa-file-excel-o'> {{options.csv.label}}</i></button>\n      </div>\n    </div>"
                },] },
    ];
    /** @nocollapse */
    TableComponent.ctorParameters = function () { return []; };
    TableComponent.propDecorators = {
        'items': [{ type: Input },],
        'fields': [{ type: Input },],
        'options': [{ type: Input },],
        'action': [{ type: Output },],
    };
    return TableComponent;
}());
//# sourceMappingURL=table.component.js.map