<script>
  import OverlayIsland from '$lib/islands/overlay-island.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import Reason from '$lib/raw-fetchers/reason.svelte';
  import { uuid } from '$lib/stores/uuid';
  export let detail = {
    uid: '',
    rid: '',
    headcode: '',
    show: true
  };
  export let close;

  function handleClick() {
    close();
  }

  async function getTrain(rid) {
    try {
      console.log(`Requested Station: ${rid}`);
      const url = `https://owlboard.info/api/v2/live/train/rid/${rid}`;
      const opt = {
        method: 'GET',
        headers: {
          uuid: $uuid
        }
      };
      const data = await fetch(url, opt);
      return await data.json();
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }

  async function parseDelay(location) {
    let string, state;
    if (location?.lateness) {
      try {
        const result = Math.floor(location.lateness / 60);
        if (result === 0) {
          (string = 'RT'), (state = '');
        } else if (result < 0) {
          (string = -result + 'E'), (state = 'early');
        } else if (result > 0) {
          (string = result + 'L'), (state = 'late');
        }
      } catch {
        (string = ''), (state = '');
      }
    } else if (location.arrivalType === 'Delayed') {
      (string = ''), (state = 'late');
    } else {
      (string = ''), (state = 'noreport');
    }
    return {
      string: string,
      state: state
    };
  }

  function parseTime(date) {
    const parsedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    return parsedTime !== 'Invalid Date' ? parsedTime : null;
  }

  function parseTimes(service) {
    const sta = new Date(service.sta),
      eta = new Date(service.eta),
      ata = new Date(service.ata);
    const std = new Date(service.std),
      etd = new Date(service.etd),
      atd = new Date(service.atd);
    let parsedSta = parseTime(sta),
      parsedEta = parseTime(eta),
      parsedAta = parseTime(ata);
    let parsedStd = parseTime(std),
      parsedEtd = parseTime(etd),
      parsedAtd = parseTime(atd);
    if (service.isCancelled) {
      (parsedEta = 'CANC'), (parsedEtd = 'CANC');
    }
    let times = {
      sta: parsedSta || '-',
      eata: parsedEta || parsedAta || '-',
      aEst: parsedEta ? 'estimate' : '',
      std: parsedStd || '-',
      eatd: parsedEtd || parsedAtd || '-',
      dEst: parsedEtd ? 'estimate' : ''
    };
    if (service.isCancelled) {
      (parsedEta = 'CANC'), (parsedEtd = 'CANC');
      (times.aEst = 'canc'), (times.dEst = 'canc');
    }
    return times;
  }
</script>

<OverlayIsland>
  <div id="detailBox">
    {#await getTrain(detail.rid)}
      <h6>{detail.headcode}</h6>
      <Loading />
    {:then train}
      <h6>{train.GetServiceDetailsResult.operatorCode}: {detail.headcode}</h6>
      <button type="button" id="closeService" on:click={handleClick}>X</button>
      <p>
        Locations in grey are not scheduled stops
        <br />
        Times in <span class="estimate">yellow</span> are estimated times
      </p>
      <table id="detailTable">
        {#if train.GetServiceDetailsResult.delayReason}
          <tr
            ><td colspan="7" class="late">
              <Reason type="delay" code={train.GetServiceDetailsResult.delayReason} />
            </td></tr
          >
        {/if}
        {#if train.GetServiceDetailsResult.cancelReason}
          <tr
            ><td colspan="7" class="canc">
              <Reason type="cancel" code={train.GetServiceDetailsResult.cancelReason} />
            </td></tr
          >
        {/if}
        <tr>
          <th colspan="2" />
          <th colspan="2">Arrival</th>
          <th colspan="2">Departure</th>
          <th />
        </tr>
        <tr>
          <th class="tableLocation">Location</th>
          <th class="tablePlatform">Pl.</th>
          <th class="tableTime">Sch</th>
          <th class="tableTime">Est/Act</th>
          <th class="tableTime">Sch</th>
          <th class="tableTime">Est/Act</th>
          <th class="tableDelay" />
        </tr>
        {#each train.GetServiceDetailsResult.locations.location as location}
          <tr>
            <td class={location?.isPass === 'true' ? 'pass' : ''}>{location.tiploc}</td>
            <td class={location?.isPass === 'true' ? 'pass' : ''}>{location.platform || ''}</td>
            {#await parseTimes(location)}
              <td />
              <td />
              <td />
              <td />
            {:then times}
              <td class={location?.isPass === 'true' ? 'pass' : ''}>{times.sta}</td>
              <td class="{location?.isPass === 'true' ? 'pass' : ''} {times.aEst}">{times.eata}</td>
              <td class={location?.isPass === 'true' ? 'pass' : ''}>{times.std}</td>
              <td class="{location?.isPass === 'true' ? 'pass' : ''} {times.dEst}">{times.eatd}</td>
            {/await}
            {#await parseDelay(location)}
              <td>-</td>
            {:then delay}
              <td class={delay.state}>{delay.string}</td>
            {/await}
          </tr>
        {/each}
      </table>
    {:catch}
      <h6>Error loading data</h6>
    {/await}
  </div>
</OverlayIsland>

<style>
  #detailBox {
    width: 100%;
    min-height: 100px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  h6 {
    position: absolute;
    top: -25px;
    left: 20px;
    font-size: 18px;
  }
  p {
    margin-top: 45px;
    margin-bottom: 0px;
  }
  #closeService {
    position: absolute;
    top: 10px;
    right: 10px;
    border: none;
    border-radius: 60px;
    width: 35px;
    height: 35px;
    background-color: var(--main-bg-color);
    color: white;
    font-weight: 700;
    font-size: 16px;
  }
  #detailTable {
    width: 100%;
    margin-top: 10px;
    color: white;
    font-size: 16px;
  }
  .tableLocation {
    width: 25%;
  }
  .tablePlatform {
    width: 8%;
  }
  .tableTime {
    width: 15%;
  }
  .tableDelay {
    width: 7%;
  }
  .estimate {
    color: rgb(255, 255, 50);
  }
  .pass {
    opacity: 0.45;
    font-size: 16px;
  }
  .canc {
    animation: pulse-cancel 1.5s linear infinite;
  }

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

  .late {
    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>
