<template>
  <transition name="itf-toast-fade" mode="in-out">
    <div
      v-show="show"
      class="itf-toast-wrapper d-print-none"
      :style="{ width }"
      :class="wrapperClassName"
    >
      <toast-message
        :class="className"
        :type="type"
        :content="message"
        :button="button"
        :on-click="onClick"
        :closable="showClose"
        :is-collapsed="isCollapsed"
        @close="close"
        :title="title"
        :support-html="supportHTML"
        @mouseenter.native="clearTimer"
        @mouseleave.native="startTimer"
      >
        <template slot="icon">
          <img v-if="iconImg" :src="iconImg" class="m-message--icon">
          <!--          <icon v-else-if="type" :name="type" class="m-message&#45;&#45;icon"/>-->
        </template>
      </toast-message>
    </div>
  </transition>
</template>
<script>
import { Vue, Component, Watch } from 'vue-property-decorator';
import ToastMessage from './ToastMessage.vue';

export default @Component({
  name: 'itfToastContainer',
  components: {
    ToastMessage
  }
})
class itfToastContainer extends Vue {
  data() {
    return {
      show: false,
      type: '',
      iconImg: '',
      title: '',
      message: '',
      duration: 3000,
      showClose: false,
      isCollapsed: false,
      width: '',
      className: '',
      wrapperClassName: '',
      button: '',
      supportHTML: false,
      onClose: null,
      onClick: null,
      timer: null,
      closed: false
    };
  }

  @Watch('closed')
  onClosed(val) {
    if (val) {
      this.show = false;
      this.$el.addEventListener('animationend', this.destroyElement);
    }
  }

  mounted() {
    if (this.type !== 'loading') {
      this.startTimer();
      if (this.duration <= 0) {
        this.showClose = true;
      }
    }
  }

  close() {
    this.closed = true;
    if (typeof this.onClose === 'function') {
      this.onClose(this);
    }
  }

  clearTimer() {
    clearTimeout(this.timer);
  }

  startTimer() {
    if (this.duration > 0 && this.type !== 'loading') {
      this.timer = setTimeout(() => {
        if (!this.closed) {
          this.close();
        }
      }, this.duration);
    }
  }

  destroyElement() {
    this.$el.removeEventListener('transitionend', this.destroyElement);
    this.$destroy(true);
    this.$el.parentNode.removeChild(this.$el);
  }
};
</script>
