<script>
  export let station = "";
  import { onMount } from 'svelte'
  import Loading from '$lib/navigation/loading.svelte';

  let requestedStation;
  $: requestedStation = station;

  let jsonData = null;
  let services = [];
  let dataAge = null;
  let isLoading = true;

  $: {
    if (jsonData === null && requestedStation) {
      fetchData();
    }

    if (jsonData && jsonData.GetStationBoardResult && jsonData.GetStationBoardResult.generatedAt) {
      dataAge = new Date(jsonData.GetStationBoardResult.generatedAt);
    }

    if (jsonData && jsonData.GetStationBoardResult && jsonData.GetStationBoardResult.trainServices && jsonData.GetStationBoardResult.trainServices.service) {
      services = jsonData.GetStationBoardResult.trainServices.service;
    } else {
      services = [];
    }
  }

  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>

  <table>
    <tr>
      <th class="from">From</th>
      <th class="to">To</th>
      <th class="plat">Plat.</th>
      <th class="time">Sch Arr.</th>
      <th class="time">Exp Arr.</th>
      <th class="time">Sch Dep.</th>
      <th class="time">Exp Dep.</th>
    </tr>
    {#each services as service}
      <tr>
        <td class="origdest from">{service.origin?.location?.locationName || ''}</td>
        <td class="origdest to">{service.destination?.location?.locationName || ''}</td>
        <td class="plat">{service.platform || '-'}</td>
        <td class="time">{parseTime(service.sta).data}</td>
        <td class="time {parseTime(service.eta).changed}">{parseTime(service.eta).data}</td>
        <td class="time">{parseTime(service.std).data}</td>
        <td class="time {parseTime(service.etd).changed}">{parseTime(service.etd).data}</td>
      </tr>
      <!-- service-detail elements are currently contained within the 'From' column
           It should be underneath the row.  I will need to look at the vanilla interface
           to establish what I did differently there. Or, I can insert a new row
           with colspan="7" to add a row spanning all columns.-->
      <tr><td colspan="7">
        <p class="service-detail">
          A {service.operator || 'Unknown'} service
          {#if service['length']}
            with {service['length'] || 'some'} coaches
          {/if}
        </p>
        {#if service.delayReason}
          <p class="service-detail">{service.delayReason}</p>
        {/if}
        {#if service.cancelReason}
          <p class="service-detail">{service.cancelReason}</p>
        {/if}
      </td></tr>
    {/each}
  </table>
{/if}
<style>
  #timestamp {
    margin: auto;
    text-align: left;
  }
  table {
    width: 100%;
    margin: auto;
    color: white;
    font-size: 13px;
  }
  .service-detail {
    color: cyan;
    text-align: left;
    font-size: 12px;
    padding: 0;
    margin: 0;
  }
@media (min-width: 800px) {
    table {font-size: 15px;}
    .service-detail {font-size: 14px;}
}
@media (min-width: 1000px) {
    table {font-size: 17px;}
    .service-detail{font-size: 16px;}
}
@media (min-width: 1600px) {
    table {font-size: 19px;}
    .service-detail {font-size: 18px;}
}
  .origdest {
    color: yellow;
    text-align: left;
  }
  .from {
    width: 25%;
  }
  .to {
    width: 25%;
  }
  .plat {
    width: 10%
  }
  .time {
    width: 10%;
  }
  .changed{
    animation: pulse-change 1.5s linear infinite;
}

.cancelled {
    animation: pulse-cancel 1.5s linear infinite;
}

@keyframes pulse-change {
    50% {
        color: var(--main-warning-color);
    }
}

@keyframes pulse-cancel {
    50% {
        color: var(--main-alert-color);
    }
}
</style>
