<template>
  <base-fieldset
    :label="label">
    <div
      v-for="(value, $index) in values"
      :key="$index">
      <div
        class="is-flex"
        style="align-items: center;">
        <key-value-field
          :value="value"
          :metakey="metakey"
          :metavalue="metavalue"
          :disabled="disabled !== false"
          @input="onInput($event, $index)" />
        <base-button
          v-if="disabled === false"
          type="invisible"
          @click="onRemove(value)">
          <base-icon value="trash-alt" />
          <span>Remove</span>
        </base-button>
      </div>
    </div>
    <div>
      <base-button
        v-if="disabled === false"
        type="secondary"
        @click="onAdd()">
        <base-icon value="plus" />
        <span>Aggiungi</span>
      </base-button>
    </div>
  </base-fieldset>
</template>

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

import InputEvent from '../../core/events/InputEvent'

import BaseFieldset from '../../elements/form/BaseFieldset.vue'
import BaseButton from '../../elements/button/BaseButton.vue'
import BaseIcon from '../../elements/icon/BaseIcon.vue'

import KeyValueField from '../field/KeyValueField.vue'

interface Dictionary {
  [metakey: string]: any;
}

@Component({
  components: {
    BaseFieldset,
    BaseButton,
    BaseIcon,
    KeyValueField
  }
})
export default class KeyValueFieldset extends Vue {
  @Prop() label!: string
  @Prop({ default () { return [] } }) values!: Dictionary[]
  @Prop({ default: false }) disabled!: boolean
  @Prop({ default: 'key' }) metakey!: string
  @Prop({ default: 'value' }) metavalue!: string

  onInput ($event: InputEvent<Dictionary>, $index: number) {
    const value = $event.value!

    const values = cloneDeep(this.values)
    values[$index][this.metakey] = value[this.metakey]
    values[$index][this.metavalue] = value[this.metavalue]

    const event = new InputEvent<Dictionary[]>()
    event.value = values
    this.$emit('input', event)
  }

  get hasAnyValueWithoutKey () {
    const valuesWithoutKey = this.values.filter((value) => {
      return value[this.metakey] === ''
    })
    return valuesWithoutKey.length === 0
  }

  onAdd () {
    if (this.hasAnyValueWithoutKey) {
      const values = cloneDeep(this.values)
      values.push({
        [this.metakey]: '',
        [this.metavalue]: ''
      })
      const event = new InputEvent<Dictionary[]>()
      event.value = values
      this.$emit('input', event)
    }
  }

  onRemove (removed: Dictionary) {
    let values = cloneDeep(this.values)
    values = values.filter((value: Dictionary) => {
      return value[this.metakey] !== removed[this.metakey]
    })
    const event = new InputEvent<Dictionary[]>()
    event.value = values
    this.$emit('input', event)
  }
}
</script>
