/* Fetch Functions */
async function publicLdb(stn) {
  var url = `${window.location.origin}/api/v1/ldb/${stn}`
  console.time('Time: Fetch LDB Data')
  var resp = await fetch(url)
  console.timeEnd('Time: Fetch LDB Data')
  return await resp.json()
}

/* Set page heading */
async function setHeaders(title,time) {
  var prefix = 'OwlBoard - '
  document.title = `${prefix}${title}`
  document.getElementById('stn_name').textContent = title
  document.getElementById('fetch_time').textContent = time.toLocaleTimeString()
  sessionStorage.setItem('board_location', title)
}

/* Display No Trains Message */
async function displayNoTrains() {
  log('No Trains', 'WARN')
  document.getElementById('no_services').style = 'display: block;'
  hideLoading()
}

/* Parse the value of `platform` to account for unknown platforms */
async function parsePlatform(svc){
  if (svc.platform != undefined) {
    var platform = svc.platform
  } else {
    var platform = '-'
  }
  if (svc.platformChanged) { // Not present in public API, ready for staff version.
    var changed = 'changed'
  } else {
    var changed = ''
  }
  return {num: platform, change: changed}
}


/* Change value of time strings to fit well on small screens */
async function parseTime(string){
  switch (string) {
  case 'Delayed':
    var output = 'LATE'
    var change = 'changed'
    break
  case 'Cancelled':
    var output = 'CANC'
    var change = 'cancelled'
    break
  case 'On time':
    var output = 'RT'
    var change = ''
    break
  case '':
    var output = '-'
    var change = ''
    break
  case undefined:
    var output = '-'
    var change = ''
    break
  case 'No report':
    var output = '-'
    var change = ''
    break
  case 'undefined':
    var output = false
    var change = ''
    break
  default:
    var output = string
    var change = 'changed'
  }
  return {data: output, changed: change}
}

/* Convert multiple Origin/Destinations to single string */
async function parseName(location) {
  if (Array.isArray(location)) {
    var name = `${location[0]['locationName']} & ${location[1]['locationName']}`
    return name
  }
  else {
    return location.locationName
  }
}

// Display Alert Messages
async function displayAlerts(array) {
  var counter = 0
  var messages = ''
  for(var i = 0; i < array.length; i++) {
    // Increment counter
    counter += 1
    // Reset Vars
    messages += `<p>${array[i]}</p>`
  }
  if (counter > 0) {
    document.getElementById('alerts_msg').insertAdjacentHTML('beforeend', messages)
    document.getElementById('alerts').style = 'display:block'
    document.getElementById('alerts_bar').style = 'display:block'
    if (counter == 1) {
      document.getElementById('alert_bar_note').textContent = `There is ${counter} active alert`
    } else if (counter > 1) {
      document.getElementById('alert_bar_note').textContent = `There are ${counter} active alerts`
    }
    return true
  }
  return false
}


/* Show/Hide alerts box */
async function inflateAlerts() {
  document.getElementById('alerts_msg').style = 'display:block;'
  document.getElementById('alert_expand_arrow').style = 'transform: rotate(180deg);'
  document.getElementById('alerts_bar').setAttribute('onclick', 'deflateAlerts()')
}

async function deflateAlerts() {
  document.getElementById('alerts_msg').style = 'display.none;'
  document.getElementById('alert_expand_arrow').style = 'transform: rotate(0deg);'
  document.getElementById('alerts_bar').setAttribute('onclick', 'inflateAlerts()')
}

/*//// SERVICE DETAIL LISTS ////*/
// Build calling list:  -- This outputs calling point data to sessionStorage in the format: key{pre: [{PREVIOUS_Stops}], post: [{POST_STOPS}]}
async function buildCallLists(svc) {
  var sSvcId = svc.serviceID
  var oSvcData = {
    plat: svc.platform,
    sta: svc.sta,
    eta: svc.eta,
    std: svc.std,
    etd: svc.etd
  }
  try {
    if (typeof svc.previousCallingPoints.callingPointList.callingPoint != 'undefined') {
      let array = await makeArray(svc.previousCallingPoints.callingPointList.callingPoint)
      oSvcData.pre = array
    }
  } catch (err) { /* Do nothing if ERR */ }
  try {
    if (typeof svc.subsequentCallingPoints.callingPointList.callingPoint != 'undefined') {
      let array = await makeArray(svc.subsequentCallingPoints.callingPointList.callingPoint)
      oSvcData.post = array
    }
  } catch (err) { /* Do nothing if ERR */ }
  sessionStorage.setItem(sSvcId, JSON.stringify(oSvcData))
}

/* Display calling list: - Read data from sessionStorage and write to DOM. */
async function showCalls(id) {
  log(`Showing details for service ${id}`, 'INFO')
  var svcDetail = await JSON.parse(sessionStorage.getItem(id))
  var pre = ''
  var post = ''
  if (typeof svcDetail.pre != 'undefined') {
    for(var preCall = 0; preCall < svcDetail.pre.length; preCall++) {
      pre += await singleCall(svcDetail.pre[preCall])
    }
  }
  if (typeof svcDetail.post != 'undefined') {
    for(var postCall = 0; postCall < svcDetail.post.length; postCall++) {
      post += await singleCall(svcDetail.post[postCall])
    }
  }
  /* Run retreived data through parsers */
  var thisStd = await parseTime(svcDetail.std)
  var thisEtd = await parseTime(svcDetail.etd)
  var thisSta = await parseTime(svcDetail.sta)
  var thisEta = await parseTime(svcDetail.eta)
  /* Prepare data for this station */
  if (thisStd.data != '-') {
    var sTime = `${thisStd.data}`
    var eTime = `${thisEtd.data}`
    var change = thisEtd.changed
  } else {
    var sTime = `${thisSta.data}`
    var eTime = `${thisEta.data}`
    var change = thisEta.changed
  };

  let here = `<tr>
                  <td class="detail-name detail-name-here detail-table-content">${sessionStorage.getItem('board_location')}</td>
                  <td class="detail-table-content">${sTime}</td>
                  <td class="detail-table-content ${change}">${eTime}</td>
                </tr> `
  /* Prepare then insert DOM Data */
  let dom = ` <div id="${id}" class="call-data">
                  <p class="close-data" onclick="hideCalls('${id}')">X</p>
                  <table class="call-table">
                    <tr>
                      <th class="detail-name-head">Location</th>
                      <th class="time">Schedule</th>
                      <th class="time">Act/Est</th>
                    </tr>
                    ${pre}
                    ${here}
                    ${post}
                  </table>
                </div>`

  document.body.insertAdjacentHTML('beforeend', dom)
  document.getElementById(id).style = 'display: block;'
  return
}

async function hideCalls(id) {
  let element = document.getElementById(id)
  element.style = 'display: none;'
  element.remove()
  return
}

/* Builds the train data information in to a table row */
async function singleCall(data) {
  if (typeof data.et != 'undefined') {
    var time = await parseTime(data.et)
  } else if (typeof data.at != 'undefined') {
    var time = await parseTime(data.at)
  }
  return `<tr>
              <td class="detail-name detail-table-content">${data.locationName}</td>
              <td class="detail-table-content">${data.st}</td>
              <td class="detail-table-content ${time.changed}">${time.data}</td>
            </tr>`
}

/* Error Handler */
async function errorHandler() {
  if (sessionStorage.getItem('failcount')) {
    var errCount = parseInt(sessionStorage.getItem('failcount'))
  } else {
    var errCount = 0
  }
  errCount += 1
  sessionStorage.setItem('failcount', errCount.toString())
  if (errCount < 10){
    await delay(3000)
    vibe('err')
    location.reload()
  } else {
    sessionStorage.removeItem('failcount')
    window.location.assign('conn-err.html')
  }
}