/* Page Init: */
// Run the init function at page load.
init()

/* Init function */
async function init() { // Gets query string and then fetch API response and pass to parsing function
  console.time('Time: Init to Complete')
  setLoadingDesc('Loading\nservices')
  var stn = await getQuery('stn')
  setLoadingDesc(`Loading\n${stn.toUpperCase()}`)
  log(`init: Looking up: ${stn}`)
  var sv = await getQuery('sv')
  log(`init: Staff Version: ${sv}`)
  if (sv === 'true') {
    log('init: Staff Version not supported yet.')
    log('init: Unable to proceed.')
  } else {
    let data
    try {
      data = await publicLdb(stn)
      setLoadingDesc(`${stn.toUpperCase()}\nParsing Data`)
      log('simple-board.init: Fetched LDB Data', 'INFO')
    } catch (err) {
      data = 'err'
      setLoadingDesc('Waiting\nConnection')
      log(`simple-board.init: Error fetching data: ${err}`, 'ERR')
    }
    parseLdb(data)
  }
}

/* Check for any errors in data returned from the Fetch call
   If no errors, if there are none, call buildPage(). */
async function parseLdb(data) {
  if (data.ERROR == 'NOT_FOUND') { // Station not found
    hideLoading()
    document.getElementById('error_notice').style = 'display: block;'
    document.getElementById('err_not_found').style = 'display: block;'
    setHeaders('Not Found',new Date())
  } else if (data == false) {  // No data for station
    hideLoading()
    document.getElementById('error_notice').style = 'display: block;'
    document.getElementById('err_no_data').style = 'display:block;'
    setHeaders('No Data',new Date())
  } else if (data == 'err') {  // Connection Error
    await delay(2000)
    hideLoading()
    document.getElementById('error_notice').style = 'display: block;'
    document.getElementById('err_conn').style = 'display: block;'
    setHeaders('Connection Error',new Date())
    showLoading()
    await delay(5000)
    log('parseLdb: Passing to error handler', 'ERR')
    errorHandler()
  } else {
    buildPage(data)
  }
}

// Build and Display Functions
async function buildPage(data) {
  setLoadingDesc('Loading\nData')
  var stationName = data.GetStationBoardResult.locationName
  log(`buildPage: Data ready for ${stationName}`)
  var generateTime = new Date(await data.GetStationBoardResult.generatedAt)
  log(`buildPage: Data prepared at ${generateTime.toLocaleString()}`)
  setHeaders(stationName, generateTime)
  // Check for notices and if true pass to function
  if (data.GetStationBoardResult.nrccMessages) {
    setLoadingDesc('Loading\nAlerts')
    await displayAlerts(await makeArray(data.GetStationBoardResult.nrccMessages.message))
  }
  if (data.GetStationBoardResult.trainServices) {
    setLoadingDesc('Loading\nTrains')
    displayTrains(await makeArray(data.GetStationBoardResult.trainServices.service))
  } else {
    displayNoTrains()
  }
  if (data.GetStationBoardResult.ferryServices) {
    setLoadingDesc('Loading\nFerries')
    displayFerry(await makeArray(data.GetStationBoardResult.ferryServices.service))
  }
  if (data.GetStationBoardResult.busServices) {
    setLoadingDesc('Loading\nBusses')
    displayBus(await makeArray(data.GetStationBoardResult.busServices.service))
  }
  hideLoading()
  console.timeEnd('Time: Init to Complete')
}


async function displayTrains(data) { // Iterated through train services and passes API sections to other functions
  log('simple-board.displayTrains: Inserting data in DOM')
  for(var i = 0; i < data.length; i++) {
    // Reset Vars
    var svc = data[i]
    displayService(svc)
    buildCallLists(svc)
  }
  document.getElementById('output').style = 'display:block;'
  log('simple-board.displayTrains: Insertion complete')
}

async function displayFerry(ferrySvc) { // Iterates through each ferry service and passes to another function
  for(var i = 0; i < ferrySvc.length; i++) {
    displayFerryService(ferrySvc[i])
  }
}

async function displayBus(busSvc) { // Iterates through each bus service and passes to other functions.
  for(var i = 0; i < busSvc.length; i++) {
    displayBusService(busSvc[i])
    buildCallLists(busSvc[i])
  }
}

async function displayService(svc) { // Creates a table row from each train service.
  var table = document.getElementById('output')
 
  // Determine Time Message
  var sta = await parseTime(svc.sta)
  var eta = await parseTime(svc.eta)
  var std = await parseTime(svc.std)
  var etd = await parseTime(svc.etd)
  // Determine Platform Message
  //if (svc.platform != undefined){var plt = svc.platform} else {var plt = "-"};
  var plt = await parsePlatform(svc)
  // Define Table Row
  var row = `
    <table>
      <tr>
        <td class="name name-item" onclick="showCalls('${svc.serviceID}')">${await parseName(svc.origin.location)}</td>
        <td class="name name-item" onclick="showCalls('${svc.serviceID}')">${await parseName(svc.destination.location)}</td>
        <td class="plat ${plt.changed}">${plt.num}</td>
        <td class="time">${sta.data}</td>
        <td class="time ${eta.changed}">${eta.data}</td>
        <td class="time">${std.data}</td>
        <td class="time ${etd.changed}">${etd.data}</td>
      </tr>
    </table>`
  // Put Table Row
  table.insertAdjacentHTML('beforeend', row)
  // Display Operator where provided (it always will be, I think)
  if (svc.operator) {
    var opRow = `<p class="msg op">A ${svc.operator} service`
    if (svc.length) { // Displays number of carriages where provided
      opRow += ` with ${svc.length} carriages</p>`
    } else {
      opRow += '</p>'
    }
    table.insertAdjacentHTML('beforeend', opRow)
  }
  // Parse cancelReason and then delayReason
  if (svc.cancelReason) {
    var cancelRow = `<p class="msg">${svc.cancelReason}</p>`
    table.insertAdjacentHTML('beforeend', cancelRow)
  }
  if (svc.delayReason) {
    var delayRow = `<p class="msg">${svc.delayReason}</p>`
    table.insertAdjacentHTML('beforeend', delayRow)
  }    
}

async function displayFerryService(svc) { // Creates a table for for each ferry service
  var table = document.getElementById('ferry')
  log(JSON.stringify(svc))
  // Determine Time Message
  var sta = await parseTime(svc.sta)
  var eta = await parseTime(svc.eta)
  var std = await parseTime(svc.std)
  var etd = await parseTime(svc.etd)
  // Determine Platform Message
  var plt = ''
  // Define Table Row
  var row = `
    <table>
      <tr>
        <td class="name name-item">${await parseName(svc.origin.location)}</td>
        <td class="name name-item">${await parseName(svc.destination.location)}</td>
        <td class="plat}">${plt}</td>
        <td class="time">${sta.data}</td>
        <td class="time ${eta.changed}">${eta.data}</td>
        <td class="time">${std.data}</td>
        <td class="time ${etd.changed}">${etd.data}</td>
      </tr>
    </table>`
  // Put Table Row
  table.insertAdjacentHTML('beforeend', row)
  // Parse cancelReason & delayReason
  if (svc.cancelReason) {
    var cancelRow = `<p class="msg">${svc.cancelReason}</p>`
    table.insertAdjacentHTML('beforeend', cancelRow)
  }
  if (svc.delayReason) {
    var delayRow = `<p class="msg">${svc.delayReason}</p>`
    table.insertAdjacentHTML('beforeend', delayRow)
  }
  document.getElementById('ferry').style = 'display:block'
}

async function displayBusService(svc) { // Creates a table row for each bus service.
  var table = document.getElementById('bus')
  log(JSON.stringify(svc))
  // Determine Time Message
  var sta = await parseTime(svc.sta)
  var eta = await parseTime(svc.eta)
  var std = await parseTime(svc.std)
  var etd = await parseTime(svc.etd)
  // Determine Platform Message
  var plt = ''
  // Define Table Row
  var row = `
    <table>
      <tr>
        <td class="name name-item" onclick="showCalls('${svc.serviceID}')">${svc.origin.location.locationName}</td>
        <td class="name name-item" onclick="showCalls('${svc.serviceID}')">${svc.destination.location.locationName}</td>
        <td class="plat}">${plt}</td>
        <td class="time">${sta.data}</td>
        <td class="time ${eta.changed}">${eta.data}</td>
        <td class="time">${std.data}</td>
        <td class="time ${etd.changed}">${etd.data}</td>
      </tr>
    </table>`
  // Put Table Row
  table.insertAdjacentHTML('beforeend', row)
  // Display operator
  if (svc.operator) {
    var opRow = `<p class="msg op">A ${svc.operator} service</p>`
    table.insertAdjacentHTML('beforeend', opRow)
  }
  // Parse cancelReason & delayReason
  if (svc.cancelReason) {
    var cancelRow = `<p class="msg">${svc.cancelReason}</p>`
    table.insertAdjacentHTML('beforeend', cancelRow)
  }
  if (svc.delayReason) {
    var delayRow = `<p class="msg">${svc.delayReason}</p>`
    table.insertAdjacentHTML('beforeend', delayRow)
  }
  document.getElementById('bus').style = 'display:block'
}