<script>
// utils
import { isDef } from '#utils'
// vuex helpers
import { mapState } from 'vuex'

/**
 * **BaseModal** component
 */
export default {
  name: 'BaseModal',
  data () {
    return {
      clickToClose: true // Click on backdrop to close
    }
  },
  props: {
    /**
     * layer
     * @description Can be a number or "foreground". (Default: 1)
     * @type {String|Number}
     */
    layer: {
      type: [String, Number],
      default () {
        return 1
      }
    }
  },
  computed: {
    // Map state from root store
    ...mapState('Core/Modals', [
      'modals'
    ]),
    /**
     * Magic computed for modal display status
     */
    vModel: {
      get () {
        return this.modals[this.$options.name].show
      },
      set (newValue) {
        this.$store.commit('Core/Modals/SET_SHOW_MODAL', {
          name: this.$options.name,
          value: newValue
        })
      }
    },
    /**
     * zIndex
     */
    zIndex: function () {
      return this.layer === 'foreground'
        ? 9999
        : (__MODALS_Z_INDEX_BASE__ + Number(this.layer))
    }
  },
  methods: {
    /**
     * Called before popup opens
     * @return {void}
     */
    onBeforeOpen: function () {
      // ... do nothing
    },
    /**
     * Called when popup close
     * @return {void}
     */
    onClosed: function () {
      // ... do nothing
    },
    /**
     * hide
     * @return {void}
     */
    hide: function () {
      this.vModel = false
    }
  },
  beforeCreate () {
    // Check if Modal name is defined and not 'BaseModal'
    if (this.$options.name === 'BaseModal') {
      this.$root.log('error', 'You must specify an unique name for the modal')
      throw new Error('You must specify an unique name for the modal')
    }
    // Get computed
    const computedOption = this.$options.computed || {}
    // Get props to map from store
    const propsToMap = Object.keys(this.$store.state.Core.Modals.modals[this.$options.name].props)
    // Loop on props
    for (const name of propsToMap) {
      if (isDef(computedOption[name])) {
        this.$root.log('error', `Computed property ${name} is already defined in ${this.$options.name}`)
        throw new Error(`Computed property ${name} is already defined in ${this.$options.name}`)
      } else {
        computedOption[name] = function () {
          return this.$store.state.Core.Modals.modals[this.$options.name].props[name]
        }
      }
    }
    // Set computed properties
    this.$options.computed = computedOption
  }
}
</script>

<style lang="scss">
._modal-overlay {
  @apply w-full;
  @apply h-full;
  @apply fixed;
  @apply left-0;
  @apply top-0;
  @apply bottom-0;
  @apply right-0;
  @apply overflow-auto;
  @apply bg-opacity-80 #{!important};
}
</style>
