<template>
  <table :class="[
    `${$classPrefix}-table`,
    {
      'bordered': border,
    }
  ]">
    <thead>
      <tr>
        <th v-if="checked" width="40px">
          <irbis-checkbox :value="isAllChecked" @change.native="checkAll"></irbis-checkbox>
        </th>
        <th v-for="(column, index) in localColumns" :key="index">{{ column.label }}</th>
      </tr>
    </thead>
    <tbody>
      <tr
        v-for="(row, index) in localData"
        :key="index"
        :class="[
        {'checked': checked && isRowChecked(row)}
      ]"
      >
        <td v-if="checked">
          <irbis-checkbox :value="isRowChecked(row)" @change.native="checkRow(row)"></irbis-checkbox>
        </td>
        <td v-for="column in localColumns">{{row[column.field]}}</td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  name: "IrbisTable",

  props: {
    data: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      default: () => []
    },
    border: {
      type: Boolean,
      default: false
    },
    checked: {
      type: Array,
      default: null
    }
  },

  data() {
    return {
      localData: this.data,
      localColumns: this.columns,
      checkedRows: this.checked
    };
  },

  computed: {
    isAllChecked() {
      let notCheckedRows = this.localData.filter(
        row => !this.isRowChecked(row)
      );
      return notCheckedRows.length > 0 ? false : true;
    }
  },

  methods: {
    isRowChecked(row) {
      return this.checkedRows.includes(row);
    },

    checkRow(row) {
      if (!this.isRowChecked(row)) {
        this.checkedRows.push(row);
      } else {
        this.removeCheckedRow(row);
      }
      this.$emit("update:checked", this.checkedRows);
      // this.$emit('check', this.checkedRows, row)
    },

    checkAll() {
      if (this.isAllChecked) {
        this.checkedRows = [];
      } else {
        // check unchecked
        this.localData.forEach(row => {
          if (!this.isRowChecked(row)) {
            this.checkRow(row);
          }
        });
      }
      this.$emit("update:checked", this.checkedRows);

      // this.$emit('check', this.checkedRows)
      // this.$emit('check-all', this.checkedRows)
    },

    removeCheckedRow(row) {
      let index = this.checkedRows.indexOf(row);
      if (index >= 0) {
        this.checkedRows.splice(index, 1);
      }
    }
  }
};
</script>