'use strict'

class XstTableCtrl {

    static get ERROR_MSG() { return 'Error on get data' }
    static get ROW_HEIGHT() { return 48 }

    static get $inject() {
        return ['$element', 'Restangular', '$mdToast', '$translate']
    }

    constructor($element, Restangular, $mdToast, $translate) {
        this.$element = $element
        this.Restangular = Restangular
        this.$mdToast = $mdToast
        this.$translate = $translate
    }

    $onInit() {
        this.query = {
            page: 1,
            limit: 5
        }

        this.columns = []

        this.options = Object.assign({
            //Default options
            dynamicResize: false
        }, this.options)

        if (this.options.dynamicResize) {
            this.calcHeight()
            $(window).resize(() => this.calcHeight())
        }

        if (this.parent) {
            this.parent.$XstTable = this
        }

        this.getList()

        this.mysrcColumns = ["displayName", "email"]
        this.search = {};
    }

    async getList() {
        try {
            if (this.endpoint) {
                this.data = (await this.Restangular.all(this.endpoint).getList()).plain()
                console.log(this.data)
            }
        } catch (error) {
            console.error(error)
            this.showMsg(XstTableCtrl.ERROR_MSG)
        }
    }

    addColumn(column) {
        this.columns.push(column)
    }

    showMsg(msg) {
        this.$mdToast.show(
            this.$mdToast.simple().textContent(msg).hideDelay(3000)
        )
    }

    get pageLabel() {
        return { page: this.$translate.instant('table.page'), of: this.$translate.instant('table.of') }
    }

    get contentHeight() {
        return this.$element.get(0).querySelector('md-card').offsetHeight
    }

    get paginationHeight() {
        return this.$element.find('.md-table-pagination').get(0).offsetHeight
    }

    get headHeight() {
        return this.$element.find('.md-head').get(0).offsetHeight
    }

    calcHeight() {
        setTimeout(() => {
            try {
                let maxSize = this.contentHeight - this.paginationHeight - this.headHeight
                this.query.limit = Math.floor(maxSize / XstTableCtrl.ROW_HEIGHT) || this.query.limit
            } catch (e) {
                console.error(e)
            }
        })
    }

}

xstTableModule.component("xstTable", {
    templateUrl: 'table.html',
    transclude: true,
    bindings: {
        options: "=?",
        endpoint: "@",
        orderby: "@",
        data: "<",
        parent: '<'
    },
    controller: XstTableCtrl,
    controllerAs: '$XstTable'
})