<template>
  <div class="layersEditor">
    <h2 class="title is-6">Custom layers</h2>

    <b-field position="is-centered">
      <b-button class="addButton" icon-left="plus-box" type="is-info" @click="addLayer" expanded> Add custom layer </b-button>
    </b-field>

    <b-field v-for="(layer, index) in layers" v-bind:key="index" grouped position="is-centered">

      <p class="control">
        <b-button icon-left="close-circle" type="is-danger" outlined @click="deleteLayer(layer)"/>
      </p>

      <b-input :placeholder="'Layer ' + index + ' name'" v-model="layer.name"/>

      <p class="control">
        <span class="file-name" v-if="layer.file">{{ layer.file.name }}</span>

        <b-upload v-else v-model="layer.file">
          <a class="button is-primary">
            <b-icon icon="upload"></b-icon>
            <span>Upload layer file</span>
          </a>
        </b-upload>
      </p>

    </b-field>
  </div>
</template>

<script>
export default {
  name: 'LayersEditor',
  props: {
    layers: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  methods: {
    addLayer () {
      this.layers.push({
        id: this.layers.length,
        name: null
      })
      this.syncToParent()
    },
    deleteLayer (layer) {
      const index = this.layers.indexOf(layer)
      if (index > -1) {
        this.layers.splice(index, 1)
      }
      this.syncToParent()
    },
    syncToParent () {
      this.$emit('update-layers', this.layers)
    }
  }
}
</script>

<style scoped>
.layersEditor h2 {
  padding: 0;
  margin: 0;
  margin-top: 15px;
}

.layersEditor .addButton {
  margin: 0;
  margin-top: 5px;
  margin-bottom: 10px;
}
</style>