import ngModule from '../../module';
import './style.scss';

export default class Table {
    constructor($scope, $element, $transclude) {
        this.$scope = $scope;
        this.table = $element[0];
        this.field = null;
        this.order = null;
    }

    setOrder(field, order) {
        this.field = field;
        this.order = order;
    }

    applyOrder(field = this.field, order = this.order) {
        if (field && order) {
            this.model.order = `${field} ${order}`;
            this.setActiveArrow();
        }

        this.model.refresh();
    }

    isScrollable() {
        return this.table.classList.contains('scrollable');
    }

    setActiveArrow() {
        let columns = this.table.querySelectorAll('vn-thead vn-th');
        columns.forEach(column => {
            column.classList.remove('active');
        });

        let selector = `vn-thead vn-th[field="${this.field}"]`;
        let activeColumn = this.table.querySelector(selector);
        activeColumn.classList.add('active');
    }
}

Table.$inject = ['$scope', '$element', '$transclude'];

ngModule.vnComponent('vnTable', {
    template: require('./index.html'),
    transclude: true,
    controller: Table,
    bindings: {
        model: '<?',
        autoLoad: '<?'
    }
});