<i18n>
{
  "en": {
    "name": "Name",
    "script": "iPXE Script",
    "titleNew": "Create entry",
    "titleExisting": "Edit entry"
  },
  "de": {
    "name": "Name",
    "script": "iPXE Script",
    "titleNew": "Eintrag erstellen",
    "titleExisting": "Eintrag bearbeiten"
  }
}
</i18n>

<template>
  <v-card style="overflow: hidden">
    <v-card-title primary-title class="dialog-title elevation-3">
      <div class="headline">{{ dialog.info.id ? $t('titleExisting') : $t('titleNew') }}</div>
    </v-card-title>
    <v-card-text>
      <v-text-field prepend-icon="label" :label="$t('name')" color="primary" v-model="name"></v-text-field>
      <div class="body-1 script-heading"><v-icon>code</v-icon><span>{{ $t('script') }}</span></div>
      <codemirror class="script-editor" ref="editor" v-model="script"></codemirror>
    </v-card-text>
    <v-divider></v-divider>
    <v-card-actions>
      <v-spacer></v-spacer>
      <v-btn flat="flat" @click="setDialog({ show: false })">{{ $t('cancel') }}</v-btn>
      <v-btn :color="dialog.info.id ? 'primary' : 'success'" @click="saveEntry">{{ dialog.info.id ? $t('save') : $t('create') }}</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
import axios from 'axios'
import { mapState } from 'vuex'

export default {
  name: 'ConfiguratorModuleEntry',
  data () {
    return {
      name: '',
      script: '',
      interval: {
        id: null,
        counter: 0
      }
    }
  },
  computed: {
    ...mapState('configurator', ['dialog'])
  },
  watch: {
    dialog: {
      immediate: true,
      deep: true,
      handler (value) {
        if (value.type === 'entry' && value.show) {
          this.name = value.info.name || ''
          this.script = value.info.script || ''
          this.interval.id = setInterval(this.refreshEditor, 50)
          this.interval.counter = 0
        }
      }
    }
  },
  methods: {
    setDialog (data) {
      this.$store.commit('configurator/setDialog', data)
    },
    async saveEntry () {
      let url = '/api/configurator/entries'
      if (this.dialog.info.id !== undefined) url += '/' + this.dialog.info.id
      await axios.post(url, {
        name: this.name,
        script: this.script
      })
      this.$store.dispatch('configurator/loadData')
      this.setDialog({ show: false })
    },
    refreshEditor () {
      this.interval.counter++
      if (this.$refs.editor) this.$refs.editor.codemirror.refresh()
      if (this.interval.counter >= 15) clearInterval(this.interval.id)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.dialog-title {
  z-index: 1;
}

.script-heading {
  display: flex;
  align-items: center;
}

.script-heading > span {
  margin-left: 9px;
}

.script-editor {
  margin-top: 8px;
}
</style>
