import Vue from 'vue'
import Overlay from './overlay.vue'
import context from './context'
import { addEvent } from '../../../src/utils/event'

export default {
  open(vm, config) {
    if (!context.stack.some(item => item.vm === vm)) {
      const el = vm.$el
      const target = el && el.parentNode ? el.parentNode : document.body
      context.stack.push({ vm, config, target })
      this.update()
    }
  },
  close(vm) {
    const { stack } = context
    if (stack.length) {
      if (context.top.vm === vm) {
        stack.pop()
        context.zIndex -= 2
        this.update()
      } else {
        context.stack = stack.filter(item => item.vm !== vm)
      }
    }
  },
  update() {
    let { overlay } = context
    if (!overlay) {
      overlay = new (Vue.extend(Overlay))({
        el: document.createElement('div'),
      })
      overlay.$on('click', this.onClick)
      addEvent(overlay.$el, 'touchmove', this.onTouchMove)
      addEvent(overlay.$el, 'webkitAnimationEnd', this.onAnimationEnd)
      addEvent(overlay.$el, 'animationend', this.onAnimationEnd)
      context.overlay = overlay
    }
    if (overlay.$el.parentNode) {
      overlay.visible = false
    }
    if (context.top) {
      const { config, target } = context.top
      target.appendChild(overlay.$el)
      Object.assign(overlay, config, {
        visible: true,
      })
    }
  },
  onClick() {
    if (context.top) {
      const { vm } = context.top
      if (vm.closeOnClickOverlay) {
        vm.$emit('input', false)
        vm.$emit('overlayClose')
      }
    }
  },
  onTouchMove(e) {
    e.preventDefault()
    e.stopPropagation()
  },
  onAnimationEnd() {
    if (context.top) {
      const { vm } = context.top
      context.activeVm = vm
      vm.openAfter()
    } else if (context.activeVm) {
      context.activeVm.closeAfter()
      context.activeVm = null
    }
  },
}
