import rtc from './rtc'
import onFind from './dom/onFind'

onFind('.LiveBlogPostListNav', (nav: HTMLElement) => {
  const blogId = nav.getAttribute('data-blog-id')

  // look for publish events for LiveBlogPosts
  rtc.receive(
    'brightspot.liveblog.LiveBlogPostRtcBroadcast',
    (data: unknown) => {
      const postData = data as { blogId: string }
      if (postData['blogId'] === blogId) {
        const refreshLink = nav.querySelector<HTMLElement>(
          '.LiveBlogPostListNav-refresh',
        )

        if (refreshLink) {
          refreshLink.click()
        }
      }
    },
  )
})

// Copy and create actions should not redirect and open in the same post edit frame
onFind(
  ['.LiveBlogGrid a.action-copy', '.LiveBlogGrid a.action-create'],
  (button: HTMLAnchorElement) => {
    button.target = 'postedit'
    const grid = button.closest('.Grid')
    if (!grid) {
      return
    }
    const blogNav = grid.querySelector('.LiveBlogPostListNav')
    if (!blogNav) {
      return
    }
    const blogId = blogNav.getAttribute('data-blog-id')
    let link = button.href
    if (!blogId || !link) {
      return
    }
    link += '&disableManagedRedirect=true'
    link += '&blogId=' + blogId
    button.href = link
  },
)
