<template>
    <thead>
        <tr>
            <th
                v-if="lineNumbers"
                class="line-numbers"/>

            <th
                v-if="selectable"
                class="good-table__checkbox-col"/>

            <th
                v-for="(column, index) in formattedColumnsFiltered"
                :key="index"
                :class="[
                    { 'cursor-pointer': isSortableColumn(column) && totalRowCount },
                    getClasses(index, 'th')
                ]"
                @click="($event) => { if(totalRowCount) sort($event, column)}">
                <slot
                    name="table-column"
                    :column="column"/>
            </th>
        </tr>
    </thead>
</template>

<script>
import Checkbox from './Checkbox.vue'
import * as SortUtils from './utils/sort'

export default {
    name: 'VgtTableHeader',
    props: {
        lineNumbers: {
            default: false,
            type: Boolean,
        },
        selectable: {
            default: false,
            type: Boolean,
        },
        allSelected: {
            default: false,
            type: Boolean,
        },
        allSelectedIndeterminate: {
            default: false,
            type: Boolean,
        },
        columns: {
            type: Array,
        },
        mode: {
            type: String,
        },
        totalRowCount: {
            type: Number,
        },
        typedColumns: {},

        //* Sort related
        sortable: {
            type: Boolean,
        },
        getClasses: {
            type: Function,
        },

        //* search related
        searchEnabled: {
            type: Boolean,
        },

        tableRef: {},

        paginated: {},
    },
    component: {
        Checkbox,
    },
    data() {
        return {
            timer: null,
            checkBoxThStyle: {},
            lineNumberThStyle: {},
            columnStyles: [],
            sorts: [],
            formattedColumns: [],
        }
    },
    computed: {
        formattedColumnsFiltered() {
            return this.formattedColumns.filter(col => !col.hidden)
        },
    },
    watch: {
        tableRef: {
            handler() {
                this.setColumnStyles()
            },
            immediate: true,
        },
        paginated: {
            handler() {
                if (this.tableRef) {
                    this.setColumnStyles()
                }
            },
            deep: true,
        },
    },
    mounted() {
        window.addEventListener('resize', this.setColumnStyles)
        this.formattedColumns = this.formatColumns(this.columns)
    },
    beforeDestroy() {
        if (this.timer) clearTimeout(this.timer)
        window.removeEventListener('resize', this.setColumnStyles)
    },
    methods: {
        closeFilter() {
            this.formatColumns(this.formattedColumns)
        },
        formatColumns(columns) {
            return columns.map(item => {
                if (item.filterOptions && item.filterOptions.enabled) this.$set(item, 'filterActive', false)
                if (item.subFields) this.formatColumns(item.subFields)

                return item
            })
        },
        reset() {
            this.$refs['filter-row'].reset(true)
        },
        toggleSelectAll() {
            this.$emit('on-toggle-select-all')
        },
        isSortableColumn(column) {
            const { sortable } = column
            const isSortable = typeof sortable === 'boolean' ? sortable : this.sortable
            return isSortable
        },
        sort(e, column) {
            //* if column is not sortable, return right here
            if (!this.isSortableColumn(column)) return

            if (e.shiftKey) {
                this.sorts = SortUtils.secondarySort(this.sorts, column)
            } else {
                this.sorts = SortUtils.primarySort(this.sorts, column)
            }
            this.$emit('on-sort-change', this.sorts)
        },

        setInitialSort(sorts) {
            this.sorts = sorts
            this.$emit('on-sort-change', this.sorts)
        },

        getColumnSort(column) {
            for (let i = 0; i < this.sorts.length; i += 1) {
                if (this.sorts[i].field === column.field) {
                    return this.sorts[i].type || 'asc'
                }
            }
            return null
        },

        getWidthStyle(dom) {
            if (window && window.getComputedStyle) {
                const cellStyle = window.getComputedStyle(dom, null)
                return {
                    width: cellStyle.width,
                }
            }
            return {
                width: 'auto',
            }
        },

        setColumnStyles() {
            const colStyles = []
            if (this.timer) clearTimeout(this.timer)
            this.timer = setTimeout(() => {
                for (let i = 0; i < this.columns.length; i++) {
                    if (this.tableRef) {
                        let skip = 0
                        if (this.selectable) skip++
                        if (this.lineNumbers) skip++
                        const cell = this.tableRef.rows[0].cells[i + skip]
                        colStyles.push(this.getWidthStyle(cell))
                    } else {
                        colStyles.push({
                            minWidth: this.columns[i].width ? this.columns[i].width : 'auto',
                            maxWidth: this.columns[i].width ? this.columns[i].width : 'auto',
                            width: this.columns[i].width ? this.columns[i].width : 'auto',
                        })
                    }
                }
                this.columnStyles = colStyles
            }, 200)
        },
    },
}
</script>
