<template>
  <div class="vee-json-editor-wrapper"></div>
</template>

<script>
import 'jsoneditor/dist/jsoneditor.min.css'
import JSONEditor from 'jsoneditor'

export default {
  props: {
    'value': {
      type: [Object, Array]
    }
  },
  watch: {
    value: function (newValue) {
      if (this.editor && !this.internalChange) {
        const editValue = this.editor.get()
        if (JSON.stringify(newValue) !== JSON.stringify(editValue)) {
          this.editor.set(newValue)
        }
      }
    }
  },
  data() {
    return {
      editor: null,
      error: false,
      json: this.value,
      internalChange: false
    }
  },
  mounted() {
    var self = this;
    var options = {
      modes: ['text', 'code'],
      mode: 'code',
      ace: window.ace,
      onChange () {
        try {
          var json = self.editor.get()
          self.error = false
        } catch (e) {
          self.error = true
          self.$emit('has-error')
        }
        if (!self.error) {
          self.json = json
          self.$emit('json-change', json)
          self.internalChange = true
          self.$emit('input', json)
          self.$nextTick(function () {
            self.internalChange = false
          })
        }
      }
    }
    this.editor = new JSONEditor(this.$el, options, this.json)
  }
}
</script>
<style lang="scss">
  .vee-json-editor-wrapper {
    width: 100%;
    height: 100%;
  }
</style>
