/* All Page Init */
const version = '2.0.0'

/* Feature Detectors */

/* Valid values for ${type}: localstorage, sessionstorage */
async function storageAvailable(type) {  // Currently not used
  try {
    let storage = window[type]
    let x = '__storage_test__'
    storage.setItem(x, 'test')
    storage.getItem(x)
    storage.removeItem(x)
    log(`lib.main.storageAvailable: ${type} is available`, 'INFO')
    return true
  } catch (err) {
    log(`lib.main.storageAvailable: ${type} is not available`, 'ERR')
    return false
  }
}

async function versionDisplay() { // Outputs version string on to any page with a tag with id="ver_str"
  localStorage.setItem('version', version)
  document.getElementById('ver_str').textContent = version
  return
}

/* Array Converter
   Converts a string to a single item array */
async function makeArray(data) {
  if (!Array.isArray(data)) {
    var array = []
    array.push(data)
    return array
  }
  return data
}

/* Timeouts */
/* Usage: '' */
const delay = ms => new Promise(res => setTimeout(res, ms))


/* Log Helper */
/* Maintains backwards compatibility for previous
   implementation of log helper */
async function log(msg, type) {
  const mode = 'tst'
  if (mode === 'prod' && type != 'ERR') {
    return
  }
  var time = new Date().toISOString()
  switch (type) {
  case 'ERR':
    console.error(`${time} - ${msg}`)
    break
  case 'WARN':
    console.warn(`${time} - ${msg}`)
    break
  case 'INFO':
    console.info(`${time} - ${msg}`)
    break
  default:
    console.log(`${time} - ${msg}`)
    break
  }
}

/* Show/Hide - Menu Control */
async function sidebarOpen() {
  document.getElementById('sidebar').style.width = '50%'
  document.getElementById('sidebar_open_short').style.display = 'none'
  document.getElementById('sidebar_close_short').style.display = 'block'
}
  
async function sidebarClose() {
  document.getElementById('sidebar').style.width = '0%'
  document.getElementById('sidebar_open_short').style.display = 'block'
  document.getElementById('sidebar_close_short').style.display = 'none'
}

/* Loading Box Control */
async function hideLoading() {
  document.getElementById('loading').style = 'display: none;'
}

/* DEPRECIATED: Alias for hideLoading() - Marked for removal*/
async function clearLoading() {
  log('Depreciated function called - clearLoading() - Alias to hideLoading()', 'WARN')
  hideLoading()
}

async function showLoading() {
  document.getElementById('loading').style = 'display: block;'
}

async function setLoadingDesc(desc) {
  document.getElementById('loading_desc').textContent = `${desc}`
}

/* Fetch User Settings */
async function getQuickLinks() {
  var defaults =
                ['bri','lwh','srd','mtp','rda','cfn',
                  'sml','shh','pri','avn','sar','svb']
  try {
    if (localStorage.getItem('qlOpt')) {
      var data = JSON.parse(localStorage.getItem('qlOpt'))
    } else {
      data = defaults
    }
  } catch (err) {
    data = defaults
  }
  return data.sort()
}

/* Fetch a known query parameter from the pages URL */
async function getQuery(param) {
  var params = new URLSearchParams(window.location.search)
  var query = params.get(param)
  if (query) {
    return query
  } else {
    return 'false'
  }
}

async function getApi(path,auth = false) {
  let apiVer = 'v1'
  let url = `${window.location.origin}/api/${apiVer}/${path}`
  log(`getApi: Fetching from endpoint: ${url}, Auth=${auth}`)
  if (auth) {
    let key = localStorage.getItem('uuid')
    var options = {
      method: 'GET',
      redirect: 'follow',
      headers: {
        'uuid': key
      }
    }
  } else {
    var options = {
      method: 'GET',
      redirect: 'follow'
    }
  }
  try {
    var resp = await fetch(url, options)
    var json = await resp.json()
    log(`resp.status: ${resp.status}`)
    log(`resp.json: ${json}`)
    if (resp.status != 200) {
      log(`lib.main: getApi: Response status: ${resp.status}`)
      return resp.status
    }
    if (!resp.ok) {
      log('lib.main: getApi: Fetch error')
      return false
    }
    return json
  } catch(err) {
    log(`lib.main: getApi: Caught fetch error.  Status: ${resp.status}`)
    return resp.status
  }
}

async function showHideAuthNotice() {
  let uuid = localStorage.getItem('uuid')
  if (uuid) {
    document.getElementById('auth-required').style = 'display:none'
  }
}

async function vibe(type) {
  let canVibrate = 'vibrate' in navigator || 'mozVibrate' in navigator
  if (canVibrate && !('vibrate' in navigator)){
    navigator.vibrate = navigator.mozVibrate
  }
  switch (type) {
  case 'err':
    navigator.vibrate([300])
    break
  case 'ok':
    navigator.vibrate([50,50,50])
    break
  default:
    navigator.vibrate(30)
  }
}

async function convertUnixLocal(unix) { // Convert unix time string to local
  var jsTime = unix*1000
  var dt = new Date(jsTime)
  return dt.toLocaleString()
}