<script>
  export let station = '';
  export let title = 'Loading...';
  import { onMount } from 'svelte';
  import AlertBar from '$lib/ldb/nrcc/alert-bar.svelte';
  import StaffTrainDetail from '$lib/ldb/staff/train-detail.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import { uuid } from '$lib/stores/uuid';
  import Island from '$lib/islands/island.svelte';
  import TableGenerator from './table/table-generator.svelte';

  let requestedStation = '';
  $: requestedStation = station;

  let jsonData = {};
  /**
   * @type {string | any[]}
   */
  let trainServices = [];
  /**
   * @type {string | any[]}
   */
  let busServices = [];
  /**
   * @type {string | any[]}
   */
  let ferryServices = [];
  let dataAge = new Date(0);
  let isLoading = true;
  let isErr = false;
  let errMsg = '';
  let alerts = [''];
  let detail = { show: false, rid: '', uid: '', headcode: '' };

  $: {
    // @ts-ignore
    if (jsonData?.GetBoardResult?.generatedAt) {
      // @ts-ignore
      dataAge = new Date(jsonData.GetBoardResult.generatedAt);
    }

    // @ts-ignore
    if (jsonData?.GetBoardResult?.trainServices?.service) {
      // @ts-ignore
      trainServices = ensureArray((trainServices = jsonData.GetBoardResult.trainServices.service));
    } else {
      trainServices = [];
    }

    // @ts-ignore
    if (jsonData?.GetBoardResult?.busServices?.service) {
      // @ts-ignore
      busServices = ensureArray((busServices = jsonData.GetBoardResult.busServices.service));
    } else {
      busServices = [];
    }

    // @ts-ignore
    if (jsonData?.GetBoardResult?.ferryServices?.service) {
      // @ts-ignore
      ensureArray((ferryServices = jsonData.GetBoardResult.ferryServices.service));
    } else {
      ferryServices = [];
    }

    // @ts-ignore
    if (jsonData?.GetBoardResult?.locationName) {
      // @ts-ignore
      title = jsonData.GetBoardResult.locationName;
    } else {
      title = 'Loading Board';
    }

    // @ts-ignore
    if (jsonData?.GetBoardResult?.nrccMessages) {
      // @ts-ignore
      alerts = processNrcc(jsonData.GetBoardResult?.nrccMessages?.message);
    } else {
      alerts = [];
    }
  }

  /**
   * @param {any} item
   */
  function ensureArray(item) {
    if (Array.isArray(item)) {
      return item;
    }
    return [item];
  }

  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);
      const json = await data.json();
      if (json.ERROR === 'NOT_FOUND') {
        isErr = true;
        errMsg = 'Unable to find this station';
      } else {
        jsonData = json;
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      isLoading = false;
      isErr = true;
      errMsg = 'Connection error, try again later';
    } finally {
      isLoading = false; // Clear loading state
    }
  }

  /**
   * @param {any} messages
   */
  function processNrcc(messages) {
    // Remove newlines and then <p> tags from input and append to array
    let arrMessages;
    if (!Array.isArray(messages)) {
      arrMessages = [messages];
    } else {
      arrMessages = messages;
    }
    let processedMessages = [];
    for (const message of arrMessages) {
      const msgText = message.xhtmlMessage;
      processedMessages.push(msgText.replace(/[\n\r]/g, '').replace(/<\/?p[^>]*>/g, ''));
    }
    return processedMessages;
  }

  function showDetail(rid = '', uid = '', tid = '') {
    detail = {
      rid: rid,
      uid: uid,
      headcode: tid,
      show: true
    };
  }

  function hideDetails() {
    detail = {
      rid: '',
      uid: '',
      headcode: '',
      show: false
    };
  }

  onMount(() => {
    fetchData();
  });
</script>

{#key detail}
  {#if detail.show}
    <StaffTrainDetail {detail} close={hideDetails} />
  {/if}
{/key}

{#if isLoading}
  <Loading />
{:else if isErr}
  <Island>
    <p><strong>{errMsg}</strong></p>
  </Island>
{:else}
  {#if alerts.length}
    <AlertBar {alerts} />
  {/if}
  <p class="dataTime">Data from: {dataAge.toLocaleString([])}</p>
  {#if trainServices && trainServices.length}
    <TableGenerator services={trainServices} click={showDetail} />
  {:else}
    <p id="noservices">There are no scheduled train services in the next two hours</p>
  {/if}
  {#if busServices && busServices.length}
    <img class="transport-mode-image" src="/images/transport-modes/bus.svg" alt="" />
    <br />
    <span class="transport-mode-text">Bus Services</span>
    <TableGenerator services={busServices} click={showDetail} />
  {/if}
  {#if ferryServices && ferryServices.length}
    <img class="transport-mode-image" src="/images/transport-modes/ferry.svg" alt="" />
    <br />
    <span class="transport-mode-text">Ferry Services</span>
    <TableGenerator services={ferryServices} click={showDetail} />
  {/if}
{/if}

<style>
  p.dataTime {
    margin-top: 5px;
    margin-bottom: 0px;
    font-size: 12px;
  }
  #noservices {
    margin: 20px;
    padding-top: 20px;
    color: white;
  }

  .transport-mode-image {
    width: 30px;
    margin: auto;
    padding-top: 25px;
  }
  .transport-mode-text {
    color: white;
  }
</style>
