<template>
  <div>
    <input type="hidden" :name="name" :value="JSON.stringify(columns)">
    <table class="editor-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Type</th>
          <th>Title</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(col, i) in columns">
          <td>
            <input v-model="col.name" class="form-control" type="text" style="width: 140px">
          </td>

          <td>
            <select v-model="col.type" class="form-control custom-select" style="width: 110px">
              <option v-for="t in colTypes" :value="t">{{t}}</option>
            </select>
          </td>

          <td>
            <input v-model="col.title" class="form-control" type="text" style="width: 170px">
          </td>

          <td class="text-nowrap">
            <a href="" :class="['btn', 'btn-outline-secondary', {disabled: i==0}]" @click.prevent="delCol(i)">
              <v-icon class="fa-trash-o" alt="Delete column" />
            </a><!--
            --><a href="" class="btn btn-outline-secondary" v-if="i === columns.length - 1"
                  @click.prevent="addCol()">
              <v-icon class="fa-plus" alt="Add Column" />
            </a>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style lang="scss" scoped>
  @import "base";

  table {
    border-collapse: collapse;
  }

  td, th {
    @include pr(1);
    @include py(1);
  }

  td .btn {
    @include mr(1);
  }
</style>

<script>
export default {
  props: {
    name: String,
    initialColumns: Array,
  },
  data: function() {
    return {
      columns: this.initialColumns,
      colTypes: ['string', 'int', 'float', 'bool'],
    }
  },
  methods: {
    delCol(n) {
      if (n == 0) return

      this.columns.splice(n, 1)
    },
    addCol() {
      this.columns.push({
        name: '',
        type: 'string',
        title: '',
      })
    }
  }
}
</script>
