// Toggles AutoSync
import onFind from './dom/onFind'
import Cookies from 'js-cookie'

onFind('.UpdateCalendarAutoSync', (element: HTMLElement) => {
  element.onclick = async (event) => {
    const url = element.getAttribute('href')
    if (!url) return

    event.preventDefault()

    const headers = new Headers()
    const cookies = Cookies.get('bsp.csrf')

    if (cookies) {
      headers.append('Brightspot-CSRF', cookies)
    }

    const body: FormData = new FormData()

    try {
      const response = await fetch(url, { method: 'POST', headers, body })
      const responseText = await response.text()
      const newDiv = new DOMParser()
        .parseFromString(responseText, 'text/html')
        .body.querySelector('div')
      if (newDiv) {
        element.textContent = newDiv.textContent
      }
    } catch (error) {
      console.error(error)
    }
  }
})
