<template>
  <transition
    :name="animation"
    @after-enter="afterEnter"
    @before-leave="beforeLeave"
    @after-leave="afterLeave"
  >
    <div 
      class="pui-modal-wrapper"
      v-if="!destroyed"
      v-show="isActive"
      tabindex="-1"
    >
      <div class="background" @click="close"/>
      <slot class="pui-modal-base-content animation-content" />
    </div>
  </transition>
</template>

<script>
export default {
  name: 'PModalBase',
  props: {
    value: Boolean,
    active: Boolean,
    type: String,
    title: String,
    description: String,
    animation: {
      type: String,
      default: 'zoom-in'
    },
    canClose: {
      type: Boolean,
      default: true
    },
    fullScreen: Boolean,
    destroyOnHide: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isActive: this.active || false,
      animating: !this.active,
      destroyed: !this.active
    }
  },
  methods: {
    close() {
      if (this.canClose) {
        this.$emit('close')
        this.$emit('update:active', false)
        this.$emit('update:value', false)
      }
    },
    keyPress({ key }) {
      if (this.isActive && (key === 'Escape' || key === 'Esc')) this.close()
    },
    afterEnter() {
      this.animating = false
      this.$emit('after-enter')
    },
    beforeLeave() {
      this.animating = true
    },
    afterLeave() {
      if (this.destroyOnHide) {
        this.destroyed = true
      }
      this.$emit('after-leave')
    },
  },
  watch: {
    active(value) {
      this.isActive = value
    },
    isActive(value) {
      if (value) this.destroyed = false
    },
  },
  created() {
    if (typeof window !== 'undefined') {
      document.addEventListener('keyup', this.keyPress)
    }
  },
  beforeDestroy() {
    if (typeof window !== 'undefined') {
      document.removeEventListener('keyup', this.keyPress)
    }
  },
  computed: {
    hasFooter() {
      return !!this.$slots.footer
    }
  }
}
</script>