//
// Init:
//
// Setup quick links
const ql = ['ql0','ql1','ql2','ql3','ql4','ql5','ql6','ql7','ql8','ql9','ql10','ql11']
storageAvailable('localStorage')
getQl()
// Check if already registered
ifAlreadyRegistered()
// Hide loading
hideLoading()

async function ifAlreadyRegistered() { // If already registered, show this on the page
  if (! await isRegistered()) {
    return null
  } else {
    document.getElementsByName('eml')[0].placeholder = 'Registered'
    document.getElementById('reg_text').textContent = 'You are already registered'
    document.getElementById('reg_button').textContent = 'Log Out'
  }
}

async function getQl(){ // Fetch Quick Links from localstorage
  var qlOpt = await getQuickLinks()
  if (qlOpt){
    var i = 0
    while (i < 12) {
      if (qlOpt[i] != 'undefined') {
        document.getElementById(`ql${i}`).value = qlOpt[i]
        i +=1
      }
    }
  }
}

async function setQl(){ // Fetch Quick Links from text input and save to localstorage
  await showLoading()// called as an onclick function
  var qlSet = []
  for (i in ql) {
    var opt = document.getElementById(`ql${i}`).value
    if (opt != ''){
      qlSet.push(opt)
    }
    qlSet.sort()
  }
  localStorage.setItem('qlOpt', JSON.stringify(qlSet))
  log('settings.setQl: User settings saved', 'INFO')
  await hideLoading()
  await showDone()
  vibe('ok')
  await delay(800)
  hideDone()
}

async function clearQl(){ // Clear Quick Links from localstorage
  showLoading()
  localStorage.removeItem('qlOpt')
  log('settings.setQl: User settings reset to default', 'INFO')
  getQl()
  await hideLoading()
  await showDone()
  vibe('ok')
  await delay(800)
  hideDone()
}

async function isRegistered() { // Check if a device is registered, returns BOOL
  if (localStorage.getItem('uuid')) {
    return true
    // Also need an API Call here to check if auth is working.
    // A Suitable function exists in auth.js - move it to lib.main.js
  }
  localStorage.removeItem('uuid')
  return false
}

async function register() { // Registers a device by sending POST request to API Server
  if (! await isRegistered()) {
    showLoading()
    let url = `${window.location.origin}/api/v1/register/request`
    let email = document.getElementById('eml').value
    let res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      redirect: 'follow',
      body: JSON.stringify({email: email})
    })
    if (res.status == 201) {
      showDone()
      hideLoading()
      return
    } else if (res.status == 403) {
      log(`settings.register: Error: Fetch returned: ${res.body['errorCode']}`, 'err')
      document.getElementsByName('eml')[0].placeholder = 'Not Authorised'
    }
  } else {
    logout()
  }
}

async function logout() { // Simply removed the UUID from localstorage
  localStorage.removeItem('uuid')
  location.reload()
  return
}

async function showDone() { // Diaplays the 'Done' dialogue.
  document.getElementById('done').style = 'opacity: 1; display: block'
}

async function hideDone() { // Hides the 'Done' dialogue.
  document.getElementById('done').style = 'opacity: 0; display: none'
}