<script>
    export let station = "";
    export let title = "Loading...";
    import { onMount } from 'svelte'
    import StaffTrainDetail from '$lib/ldb/staff-train-detail.svelte';
    import Loading from '$lib/navigation/loading.svelte';
	  import Nav from '$lib/navigation/nav.svelte';
    import { uuid } from '$lib/stores/uuid';
  
    let requestedStation;
    $: requestedStation = station;
  
    let jsonData = {};
    let services = [];
    let dataAge = null;
    let isLoading = true;
  
    $: {
      if (jsonData?.GetBoardResult?.generatedAt) {
        dataAge = new Date(jsonData.GetBoardResult.generatedAt);
      }
  
      if (jsonData?.GetBoardResult?.trainServices?.service) {
        services = jsonData.GetBoardResult.trainServices.service;
      } else {
        services = [];
      }

      if (jsonData?.GetBoardResult?.locationName) {
        title = jsonData.GetBoardResult.locationName
      } else {
        title = "Loading Board"
      }
    }
  
    async function fetchData() {
      isLoading = true; // Set loading state
      try {
        console.log(`Requested Station: ${requestedStation}`);
        const url = `https://owlboard.info/api/v2/live/station/${requestedStation}/staff`;
        const opt = {
            method: "GET",
            headers: {
                "uuid": $uuid
            }
        }
        const data = await fetch(url, opt);
        jsonData = await data.json();
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        isLoading = false; // Clear loading state
      }
    }
  
    function parseTime(sch, act){
      return
    }

    function parseDateTime(input) {
      const dt = new Date(input);
      const output = dt.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
      if (output !== "Invalid Date") {
        return output
      }
      return '-'
    }
  
    onMount(() => {
      fetchData();
    });
  </script>
  <p>Staff Boards not yet implemented</p>
  {#if isLoading}
    <Loading />
  {:else}
    
    <p id="timestamp">Updated: {dataAge.toLocaleTimeString()}</p>
    <table>
      <tr>
        <th class="id">ID</th>
        <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>
          <th class="id id-data data">{service.trainid}</th>
          <th class="from from-data data">{service.origin.location.tiploc}</th>
          <th class="to to-data data">{service.destination.location.tiploc}</th>
          <th class="plat plat-data data">{service.platform || '-'}</th>
          <th class="time time-data data">{parseDateTime(service.sta)}</th>
          <th class="time time-data data">{parseDateTime(service.ata || service.eta)}</th>
          <th class="time time-data data">{parseDateTime(service.std)}</th>
          {#if service.isCancelled}
            <th class="time time-data data can-time">CAN</th>
          {:else}
            <th class="time time-data data">{parseDateTime(service.atd || service.etd)}</th>
          {/if}
        </tr>
        <tr class="text-row">
          <td colspan="8" class="text-data">
            {service.operator}
          </td>
        </tr>
      {/each}
    </table>
  {/if}  

 <Nav />

 <style>
  table {
    color: white;
    font-weight: normal;
    margin: auto;
  }

  .data {
    font-weight: normal;
  }

  .id-data {
    color: lightgray;
    text-align: left;
  }

  .from-data, .to-data {
    color: yellow;
    text-decoration: none;
    text-align: left;
  }

  .text-row {
    margin-top: 0px;
    padding-bottom: 5px;
  }

  .text-data {
    text-align: left;
    color: cyan;
  }

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

.early-time {
  animation: pulse-early 1.5s linear infinite;
}

.late-time {
  animation: pulse-late 1.5s linear infinite;
}

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

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

@keyframes pulse-early {
    50% {
        color: rgb(136, 164, 255);
    }
}
 </style>