import { Application } from '../../types'

export default (moduleWindow: Window, application: Application) => {
  const realOpen = moduleWindow.open
  moduleWindow.addEventListener('click', (event: MouseEvent) => {
    const path = event['path'] || []
    const anchor = (() => {
      for (const el of path) {
        if (el.tagName === 'A') return el
      }
    })()
    if (anchor?.target === '_bank') {
      const href = anchor.href
      const title = anchor.title || ''
      const preset = anchor.getAttribute('preset')
      if (href) {
        application.pushWindow(href, title, preset).catch(() => {
          realOpen(href)
        })
        event.stopPropagation()
        event.preventDefault()
      }
    }
  })
  moduleWindow.open = (url?: string | URL | undefined, target?: string | undefined, features?: string | undefined) => {
    if (typeof url !== 'string' || target || features) {
      return realOpen(url, target, features)
    }
    if (typeof url === 'string') {
      application.pushWindow(url, '').catch(() => {
        realOpen(url)
      })
    }
    return null
  }
}
