<template>
  <div id="mergeFieldsReplacer">
    <or-modal
      ref="mergeFieldsReplacerModal"
      title="Dynamic Values Replacer"
      @hide="modalMode = ''"
    >
      <merge-fields-replacer-modal
        v-if="modalMode === 'mergeFieldsReplacer' && source !== ''"
        :source="source"
        :mode="mode"
        @merge-fileds::manage-save="manageSaveMergeFields"
      />
      
      <replaced-view-modal
        v-if="modalMode === 'replacedViewModal'"
        :source="source"
        :mode="mode"
      />
      
      <modal-footer 
        slot="footer"
        :modalMode="modalMode"
        :allowSaveMergeFields="allowSaveMergeFields"
      />
    </or-modal>
  </div>
</template>

<script>
import MergeFieldsReplacerModal from './_components/merge-fields-replacer-modal.vue';
import ReplacedViewModal from './_components/replaced-view-modal.vue';
import ModalFooter from './_components/modal-footer.vue';

export default {
  name: 'MergeFieldsReplacerModule',

  components: {
    MergeFieldsReplacerModal,
    ReplacedViewModal,
    ModalFooter
  },

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

  data () {
    return {
      modalMode: '',
      replacedString: '',
      allowSaveMergeFields: false
    };
  },

  mounted () {
    this.$EventBus.$on('merge-fields::replace', this.initModal);
    this.$EventBus.$on('merge-fields::save', this.saveMergeFields);
    this.$EventBus.$on('merge-fields::cancel', this.cancelMergeFields);
    this.$EventBus.$on('replaced-string::save', this.saveReplacedString);
    this.$EventBus.$on('replaced-string::cancel', this.cancelReplacedString);
    this.$EventBus.$on('replaced-string::generated', string => { this.replacedString = string; });
  },

  beforeDestroy () {
    this.$EventBus.$off('merge-fields::replace');
    this.$EventBus.$off('merge-fields::save');
    this.$EventBus.$off('merge-fields::cancel');
    this.$EventBus.$off('replaced-string::save');
    this.$EventBus.$off('replaced-string::cancel');
    this.$EventBus.$off('replaced-string::generated');
  },

  methods: {
    initModal () {
      this.modalMode = 'mergeFieldsReplacer';
      this.$refs['mergeFieldsReplacerModal'].open();
    },

    saveMergeFields () {
      this.modalMode = 'replacedViewModal';
    },

    cancelMergeFields () {
      this.$refs['mergeFieldsReplacerModal'].close();
    },

    saveReplacedString () {
      this.$refs['mergeFieldsReplacerModal'].close();
      this.$EventBus.$emit('merge-fields::replaced', this.replacedString);
    },

    cancelReplacedString () {
      this.modalMode = 'mergeFieldsReplacer';
    },

    manageSaveMergeFields (value) {
      this.allowSaveMergeFields = value;
    }
  }
};
</script>

<style lang="scss" scoped></style>
