<template>
  <table class="table is-fullwidth is-hoverable is-family-primary">
    <thead>
      <tr>
        <th
          class="is-narrow"
          v-if="selectable !== false" />
        <th v-for="column in template" :key="column.key">
          {{ column.label }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr
        v-for="(item, i) in values"
        :key="i"
        :class="{ 'is-selected': isSelected(item) }">
        <td
          v-if="selectable !== false">
          <base-checkbox
            :value="isSelected(item)"
            @input="onSelect($event, item)"/>
        </td>
        <td
          v-for="column in template"
          :key="`${i}[${column.key}]`"
          @click="onClick(item)"
          style="cursor: pointer;">
          {{ item[column.key] }}
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'

import BaseCheckbox from '../checkbox/BaseCheckbox.vue'
import ChangeEvent from '../../core/events/ChangeEvent'
import ClickEvent from '../../core/events/ClickEvent'
import InputEvent from '../../core/events/InputEvent'

@Component({
  name: 'base-table',
  components: {
    BaseCheckbox
  }
})
export default class BaseTable extends Vue {
  @Prop() template!: any[]
  @Prop() values !: any[]
  @Prop() metakey!: string
  @Prop({ default () { return [] } }) selected!: any[]
  @Prop({ default: false }) selectable!: boolean

  onSelect ($event: InputEvent<boolean>, item: any) {
    let selected = JSON.parse(JSON.stringify(this.selected))
    if ($event.value) {
      selected.push(item)
    } else {
      const metakey = this.metakey
      selected = selected.filter((i: any) => {
        return i[metakey] !== item[metakey]
      })
    }
    const event = new ChangeEvent<any>()
    event.value = selected
    event.oldValue = this.selected
    this.$emit('change', event)
  }

  isSelected (item: any) {
    return this.selected.some((i) => {
      return i[this.metakey] === item[this.metakey]
    })
  }

  onClick (item: any): void {
    const event = new ClickEvent<any>()
    event.value = item
    this.$emit('click', event)
  }
}
</script>

<style lang="scss" scoped>
@import "../../core/base/bulma.scss";
$table-row-active-background-color: $revas-secondary-light;
$table-row-active-color: $revas-secondary-light-invert;
@import "bulma/sass/elements/table.sass";

.is-fullwidth {
  width: 100%;
}
</style>
