<template>
  <div id="replacedViewModal">
    <or-code
      v-if="mode === 'codeEditor'"
      v-model="source"
      label="SSML Code"
      mode="html"
      disable-warnings
      readonly
    />

    <editable-area 
      v-if="mode === 'visualEditor'"
      ref="editable"
      :content="source"
      :tagList="tagList"
    />
  </div>
</template>

<script>
import JSON2XML from '../../../utils/JSON2XML.js';
import filterDependentAttributes from '../../../utils/filterDependentAttributes.js';
// eslint-disable-next-line
import EditableArea from '../../editable-module/_components/editable-area.vue';

export default {
  name: 'ReplacedViewModal',

  props: {
    // eslint-disable-next-line
    source: '',
    mode: { type: String, default: 'visualEditor' }
  },

  data () {
    return {
      replaced: ''
    };
  },

  computed: {
    mergeFields () { return this.$liteStore.get('mergeFieldsReplacer/mergeFields'); },
    tagList () {  
      return this.$liteStore.get('tagList/getTagsList'); 
    }
  },

  watch: {    
    tagList () {
      this.tagList = this.$liteStore.get('tagList/getTagsList');
    }
  },

  mounted () {
    if (this.mode === 'codeEditor') {
      this.source = this.replaceMergeFieldsInString(this.source);
      this.$EventBus.$emit('replaced-string::generated', this.source);
    }

    if (this.mode === 'visualEditor') {
      this.$nextTick(() => { this.$refs.editable.$el.contentEditable = false; });

      this.source = this.replaceMergeFieldsInJson(this.source);

      const replaced = this.replaceMergeFieldsInString(JSON2XML(filterDependentAttributes(this.source, this.$liteStore.get('tagList/getTagsList'))));
      // console.log('>>> replaced ssml => ', replaced)
      this.$EventBus.$emit('replaced-string::generated', replaced);
    }
  },

  beforeDestroy () {
    this.source = '';
  },

  methods: {
    replaceMergeFieldsInString (string) {
      this.mergeFields.forEach(mergeField => {
        string = string.replace(mergeField.original, mergeField.replacer);
      });

      return string;
    },

    replaceMergeFieldsInJson (json) {
      const mergeFields = this.mergeFields;
      
      json = json.map(function ext (obj) {
        if (obj.type === 'merge-field') {
          obj.replacer = mergeFields.find(mergeField => mergeField.original === obj.original).replacer;
        }

        if (obj.content instanceof Array) obj.content = obj.content.map(ext);

        return obj;
      });

      return json;
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ {
  #editable .text-wrapper {
    pointer-events: none;
  }
}
</style>
