<template>
  <meta-object-fieldset
    label="Example Object"
    :value="value"
    :template="template"
    @input="onInput" />
</template>

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

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

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

import MetaObjectFieldset from './MetaObjectFieldset.vue'
import KeyValueFieldset from './KeyValueFieldset.vue'

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

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

  get value () {
    const returnValue: any = {}
    this.values.forEach((value) => {
      returnValue[value[this.metakey]] = value[this.metavalue]
    })
    return returnValue
  }

  onInput (event: InputEvent<any>) {
    debugger
    const value = event.value
    const metadata = []
    for (const prop in value) {
      if (value[prop] !== undefined) continue
      metadata.push({
        [this.metakey]: prop,
        [this.metavalue]: value[prop]
      })
    }
    const newEvent = new InputEvent<Dictionary[]>()
    newEvent.value = metadata
    this.$emit('input', newEvent)
  }
}
</script>
