<script>
    export let station = "";
    export let title = "";
    import { onMount } from 'svelte'
    import Loading from '$lib/navigation/loading.svelte';
	import Nav from '$lib/navigation/nav.svelte';
  
    let requestedStation;
    $: requestedStation = station;
  
    let jsonData = {};
    let services = [];
    let dataAge = null;
    let isLoading = true;
  
    $: {
      if (jsonData === null && requestedStation) {
        fetchData();
      }
  
      if (jsonData?.GetStationBoardResult?.generatedAt) {
        dataAge = new Date(jsonData.GetStationBoardResult.generatedAt);
      }
  
      if (jsonData?.GetStationBoardResult?.trainServices?.service) {
        services = jsonData.GetStationBoardResult.trainServices.service;
      } else {
        services = [];
      }

      if (jsonData?.GetStationBoardResult?.locationName) {
        title = jsonData.GetStationBoardResult.locationName
      } else {
        title = "Loading Board"
      }
    }
  
    async function fetchData() {
      isLoading = true; // Set loading state
      try {
        console.log(`Requested Station: ${requestedStation}`);
        const data = await fetch(`https://owlboard.info/api/v1/ldb/${requestedStation}`);
        jsonData = await data.json();
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        isLoading = false; // Clear loading state
      }
    }
  
    function parseTime(string = ""){
      let output
      let change
      switch (string) {
      case 'Delayed':
        output = 'LATE'
        change = "changed"
        break
      case 'Cancelled':
        output = 'CANC'
        change = "cancelled"
        break
      case 'On time':
        output = 'RT'
        change = ""
        break
      case '':
        output = '-'
        change = ""
        break
      case undefined:
        output = '-'
        change = ""
        break
      case 'No report':
        output = '-'
        change = ""
        break
      case 'undefined':
        output = false
        change = ""
        break
      default:
        output = string
        change = "changed"
      }
      return {data: output, changed: change}
    }
  
    onMount(() => {
      if (requestedStation && jsonData === null) {
        fetchData();
      }
    });
  </script>
  
  {#if isLoading}
    <Loading />
  {:else}
    
    <p id="timestamp">Updated: {dataAge.toLocaleTimeString()}</p>
    <p>Staff LDB for {station}</p>

    <!--  REST OF PAGE HERE   -->
  {/if}  

 <Nav />