<!--
Program: Modal Container
Author: SDL
Description: Modal Container Common Component
-->
<template>
  <div id="modals-container">
    <modal
      v-bind="modal.modalAttrs"
      v-for="modal in modals"
      :key="modal.id"
      v-on="modal.modalListeners"
      @closed="remove(modal.id)"
    >
      <component
        v-bind="modal.componentAttrs"
        :is="modal.component"
        @close="$modal.hide(modal.modalAttrs.name)"
      />
    </modal>
  </div>
</template>
<script>
import { generateId } from './utils';
import { shallowRef } from 'vue';

const PREFIX = '_dynamic_modal_';

export default {
  data() {
    return {
      modals: [],
    };
  },
  created() {
    // eslint-disable-next-line no-underscore-dangle
    this.$root._dynamicContainer = this;
  },
  methods: {
    add(component, componentAttrs = {}, modalAttrs = {}, modalListeners = {}) {
      const id = generateId();
      const name = modalAttrs.name || PREFIX + id;
      const shallowComponent = shallowRef(component);

      this.modals.push({
        id,
        modalAttrs: { ...modalAttrs, name },
        modalListeners,
        component: shallowComponent,
        componentAttrs,
      });

      this.$nextTick(() => {
        this.$modal.show(name);
      });
    },
    remove(id) {
      const index = this.modals.findIndex(v => v.id === id);

      if (index !== -1) {
        this.modals.splice(index, 1);
      }
    },
  },
};
</script>
