import Vue from 'vue'
import Modal from './PluginModal'

const createElement = (marker, root, tag) => {
  let target = document.querySelector(root) || document.body

  if (target.querySelectorAll(marker).length === 0) {
    let el = document.createElement(tag || 'div')
    el.setAttribute(marker, '')
    target.appendChild(el)
  }
}

class HlsModal {
  constructor () {
    this.modals = {}
  }

  fromComponent (comp, options) {
    let destroyOnHide = options && options.destroyOnHide
    let onHide = options && options.onHide
    let onShow = options && options.onShow
    let cusClass = options && options.cusClass
    let modalId = 'modal_' + Math.random().toString(36).substr(3, 9)
    createElement(modalId)
    let ModalComponent = Vue.extend(Modal)
    let modal = new ModalComponent({
      propsData: {
        destroyOnHide: !!destroyOnHide,
        onShow: onShow,
        onHide: onHide,
        cusClass: cusClass,
      },
    })
    modal.$mount(`[${modalId}]`)

    let ContentComponent = Vue.extend(comp)
    let content = new ContentComponent()
    content.$mount(modal.$el.querySelector('[hls-modal-content]'))

    modal.id = modalId
    modal.content = content
    this.modals[modalId] = modal

    return new Promise((resolve) => {
      resolve(modal)
    })
  }

  destroy (modal) {
    if (modal) {
      modal.content && modal.content.$destroy()
      modal.$destroy()
    }
  }
}

export default new HlsModal()
