init()

async function init() {
  hideLoading()
}

async function submit() {
  setLoadingDesc('Collecting\nData')
  showLoading()
  var browserData = await getBrowserData()
  setLoadingDesc('Reading\nForm')
  var formData = await getFormData()
  preflight({browserData: browserData, formData: formData})
}

async function getFormData() {
  let data = {}
  data.subject = document.getElementById('subject').value
  data.message = document.getElementById('message').value
  return data
}

async function getBrowserData() {
  let data = {}
  data.userAgent = navigator.userAgent
  data.userAgentData = JSON.stringify(navigator.userAgentData)
  data.localStorage = JSON.stringify(await storageAvailable('localStorage'))
  data.sessionStorage = JSON.stringify(await storageAvailable('sessionStorage'))
  data.viewport = `${window.innerWidth} x ${window.innerHeight}`
  return data
}

async function preflight(data) {
  document.getElementById('pre_subject').textContent = data.formData.subject
  pre_msg = `UserAgent: ${data.browserData.userAgent}
     \nUserAgentData: ${data.browserData.userAgentData}
     \nlocalStorage Avail: ${data.browserData.localStorage}
     \nsessionStorage Avail: ${data.browserData.sessionStorage}
     \nViewport size: ${data.browserData.viewport}
     \nUser message:\n\n${data.formData.message}`
  document.getElementById('pre_message').innerText = pre_msg
  hideLoading()
  document.getElementById('preflight').style = 'display: block'
  sessionStorage.setItem('preflight_subject', data.formData.subject)
  sessionStorage.setItem('preflight_msg', pre_msg)
}

async function cancel() {
  document.getElementById('preflight').style = 'display: none'
}

async function send() {
  setLoadingDesc('Sending\nData')
  document.getElementById('preflight').style = 'display: none'
  showLoading()
  var subject = sessionStorage.getItem('preflight_subject')
  var msg = sessionStorage.getItem('preflight_msg')
  if (typeof subject != 'string') {
    subject = document.getElementById('preflight_subject').innerText
  }
  if (typeof msg != 'string') {
    msg = document.getElementById('preflight_msg')
  }
  var payload = JSON.stringify({subject: subject, msg: msg})
  console.log(payload)
  let opt = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    redirect: 'follow',
    body: payload
  }
  var res = await fetch(`${window.location.origin}/api/v1/issue`, opt)
  if (res.status == 200) {
    setLoadingDesc('Success')
    vibe('ok')
    await delay(2500)
    window.location.replace('/')
  } else {
    setLoadingDesc('Error')
    vibe('err')
    await delay(2500)
    hideLoading()
    document.getElementById('preflight').style = 'display: none;'
  }
}