<template>
    <table class="table is-stripped is-fullwidth">
        <thead>
            <tr>
                <slot name="header-head"/>
                <th v-for="col in columns" :key="col"
                    style="vertical-align: middle">{{ labels[col] }}</th>
                <slot name="header-tail"/>
            </tr>
        </thead>
        <tbody>
            <slot name="head"/>
            <template v-for="(item,row) in items" :key="row">
                <!-- data-index comes from AList component drag & drop -->
                <a-row :item="item" :cell="{row, columns}" :data-index="row"
                        :draggable="orderable"
                        @dragstart="onDragStart" @dragover="onDragOver" @drop="onDrop"
                        @cell="onCellEvent(index, $event)">
                    <template v-for="[name,slot] of rowSlots" :key="slot" v-slot:[slot]="data">
                        <template v-if="slot == 'head' || slot == 'tail'">
                            <slot :name="name" v-bind="data"/>
                        </template>
                        <template v-else>
                            <div @keydown.capture.ctrl="onControlKey($event, data.cell)">
                                <slot :name="name" v-bind="data"/>
                            </div>
                        </template>
                    </template>
                </a-row>
            </template>
            <template v-if="allowCreate">
                <a-row :item="extraItem" :cell="{row:items.length, columns}" 
                        @keypress.enter.stop.prevent="validateExtraCell">
                    <template v-for="[name,slot] of rowSlots" :key="slot" v-slot:[slot]="data">
                        <slot :name="name" v-bind="data"/>
                    </template>
                </a-row>
            </template>
            <slot name="tail"/>
        </tbody>
    </table>
</template>
<script>
import AList from './AList.vue'
import ARow from './ARow.vue'

const Component = {
    extends: AList,
    components: { ARow },
    emit: ['cell'],

    props: {
        ...AList.props,
        columns: Array,
        labels: Object,
        allowCreate: Boolean,
    },

    data() {
        return {
            ...super.data,
            extraItem: new this.set.model(),
        }
    },

    computed: {
        rowCells() {
            const cells = []
            for(var row in this.items)
                cells.push({row, columns: this.columns,})
        },

        rows() {
            return [...this.$el.querySelectorAll('tr')].filter(x => x.__row)
                                                       .map(x => x.__row)
        },
        
        rowSlots() {
            return Object.keys(this.$slots).filter(x => x.startsWith('row-'))
                                           .map(x => [x, x.slice(4)])
        },
    },

    methods: {
        validateExtraCell() {
            if(!this.allowCreate)
                return
            this.set.push(this.extraItem)
            this.extraItem = new this.set.model()
        },

        onControlKey(event, cell) {
            switch(event.key) {
                case "ArrowUp": this.focus(-1, 0, cell)
                                event.stopPropagation()
                                event.preventDefault()
                                break;
                case "ArrowDown": this.focus(1, 0, cell)
                                event.stopPropagation()
                                event.preventDefault()
                                break;
                case "ArrowLeft": this.focus(0, -1, cell)
                                event.stopPropagation()
                                event.preventDefault()
                                break;
                case "ArrowRight": this.focus(0, 1, cell)
                                event.stopPropagation()
                                event.preventDefault()
                                break;
            }
        },
    
        /**
         * React on 'cell' event, re-emitting it with additional values:
         * - `set`: data set
         * - `row`: row index
         *
         * @param {Number} row: row index
         * @param {} data: cell's event data
         */
        onCellEvent(row, event) {
            if(event.name == 'focus')
                this.cellFocus(event.data, event.cell)
            
            this.$emit('cell', {
                ...event, row,
                set: this.set
            })
        },

        getCellNode(row, col) {
            const el = this.$refs[row]
            return el && el.cellEls(col)
        },

        /**
         * Focus on a cell
         */
        focus(row, col, from=null) {
            if(from)
                row += from.row

            row = this.rows[row]
            row && row.focus(col, from)
        },
    },
}
Component.props.itemTag.default = 'tr'
Component.props.listTag.default = 'tbody'

export default Component
</script>
