<script lang="ts">
  import { fly } from 'svelte/transition';
  import { uuid } from '$lib/stores/uuid';
  import LoadingText from '$lib/navigation/loading-text.svelte';
  import StylesToc from './styles-toc.svelte';
  import { getApiUrl } from '$lib/scripts/upstream';
  import PisHandler from '$lib/train/pis-handler.svelte';

  import type { OB_TrainTT_service } from '@owlboard/ts-types';
  import TrainIcons from './trainIcons.svelte';

  export let service: OB_TrainTT_service;

  let isExpanded = false;

  async function getTrainByUID(tuid = '') {
    const url = `${getApiUrl()}/api/v2/timetable/train/now/byTrainUid/${tuid}`;
    const options = {
      method: 'GET',
      headers: {
        uuid: $uuid
      }
    };
    const res = await fetch(url, options);
    if (res.status === 200) {
      return await res.json();
    } else {
      throw new Error('Unable to Fetch');
    }
  }

  async function expand() {
    isExpanded = !isExpanded;
  }
</script>

<div class="container">
  <div class="container-header" on:click={expand} on:keypress={expand}>
    <span class="header"
      ><StylesToc toc={service?.operator || ''} />
      {service?.stops[0]['publicDeparture'] || service?.stops[0]['wttDeparture']}
      {service?.stops[0]['tiploc']} to {service?.stops[service['stops'].length - 1]['tiploc']}</span
    >
    <span id="container-arrow" class:isExpanded>V</span>
  </div>
  {#if isExpanded}
    <div class="container-detail" in:fly={{ y: -20, duration: 200 }}>
      {#await getTrainByUID(service.trainUid)}
        <LoadingText />
      {:then serviceDetail}
        {#if serviceDetail.stpIndicator === 'C'}
          <p class="text-message">
            This has been removed from the timetable for today.
          </p>
          <p class="text-message">
            The service may have been retimed, re-routed or removed from todays timetable completely.
          </p>
          <p class="text-message">
            If it has been retimed or re-routed, there is likely to be another service with the same headcode booked to run.
          </p>
        {:else}
          <div class="detailOperator"><StylesToc toc={service?.operator || ''} full={true} /></div>
          
          <TrainIcons firstClass={serviceDetail.firstClass} hasCatering={serviceDetail.catering} sleeper={serviceDetail.sleeper} vstp={serviceDetail.vstp} />
          {#if serviceDetail.pis}
            <PisHandler pisObject={serviceDetail.pis} />
          {/if}
          <p class="svc-detail">
            Planned Type: {parseInt(serviceDetail.planSpeed) || '--'}mph {serviceDetail.powerType || 'Non-Rail vehicle'}
          </p>
          <p class="svc-detail">
            Days Run: {serviceDetail?.daysRun.join(', ').toUpperCase() || 'Unknown'}
          </p>
          <p class="svc-detail validity">
            Valid From: {new Date(serviceDetail.scheduleStart).toLocaleDateString('en-GB', {
              timeZone: 'UTC'
            })} - {new Date(serviceDetail.scheduleEnd).toLocaleDateString('en-GB', {
              timeZone: 'UTC'
            })}
          </p>
          <table>
            <caption>Italics are 'pass' times, grey times are non-passenger stops</caption>
            <tr>
              <th>Location</th>
              <th>Plt.</th>
              <th>Sch Arr.</th>
              <th>Sch Dep.</th>
            </tr>
              {#each serviceDetail.stops as stop}
                <tr>
                  {#if stop.publicArrival || stop.publicDeparture}
                  <td>{stop.tiploc}</td>
                  <td>{stop.platform || '-'}</td>
                  <td>{stop.publicArrival || '-'}</td>
                  <td>{stop.publicDeparture || '-'}</td>
                  {:else if stop.wttArrival || stop.wttDeparture}
                  <td class="wtt">{stop.tiploc}</td>
                  <td class="wtt">{stop.platform || stop.depLine || stop.arrLine || '-'}</td>
                  <td class="wtt">{stop.wttArrival || '-'}</td>
                  <td class="wtt">{stop.wttDeparture || '-'}</td>
                  {:else}
                  <td class="pass">{stop.tiploc}</td>
                  <td class="pass">{stop.platform || stop.depLine || stop.arrLine || '-'}</td>
                  <td class="pass">-</td>
                  <td class="pass">{stop.pass || '-'}</td>
                  {/if}
                </tr>
              {/each}
          </table>
        {/if}
      {:catch}
        <p>Unable to fetch train data</p>
      {/await}
    </div>
  {/if}
</div>

<style>
  .container {
    position: relative;
    margin: auto;
    margin-bottom: 20px;
    width: 95%;
    max-width: 600px;
    height: auto;
    background-color: var(--island-bg-solid);
    border-radius: 10px;
    overflow: hidden;
    transition: height 500ms ease-in-out;
    box-shadow: 5px 5px 30px var(--box-shadow-color);
  }
  .container-header {
    text-align: left;
    padding-left: 10px;
    font-size: 18px;
    font-weight: 600;
    padding-top: 12px;
    padding-bottom: 10px;
    font-family: ubuntu, monospace;
    color: var(--island-text-color);
  }
  #container-arrow {
    font-family: Arial, Helvetica, sans-serif;
    font-weight: 600;
    color: var(--island-text-color);
    margin: 0;
    padding: 0;
    position: absolute;
    right: 16px;
    top: 10px;
    transition-duration: 300ms;
    z-index: 2;
  }
  .isExpanded {
    transform: rotate(180deg);
  }
  .detailOperator {
    padding-top: 15px;
    margin-bottom: 15px;
    font-weight: 600;
  }
  .svc-detail {
    margin-top: 6px;
    margin-bottom: 2px;
    color: var(--island-text-color);
  }
  .validity {
    font-size: 14px;
  }
  table {
    margin: auto;
    padding-top: 5px;
    padding-bottom: 10px;
    color: var(--island-text-color);
  }
  caption {
    padding-top: 15px;
    font-size: small;
  }
  .wtt {
    opacity: 0.5;
  }
  .pass {
    font-style: italic;
    opacity: 0.5;
  }
  .text-message {
    margin: 5px;
    margin-left: 20px;
    margin-right: 20px;
    padding-bottom: 10px;
  }
</style>
