<script lang="ts">
  import { createEventDispatcher } from 'svelte';
  import { Icon, ArrowSmallDown, ArrowSmallUp } from 'svelte-hero-icons';

  export let field: string;
  export let heading: any = field;
  export let order: null | 'asc' | 'desc' = null;
  export let sortable: boolean = true;

  function getNextSortOrder(): string | null {
    if (order === null) {
      return 'asc';
    } else if (order === 'asc') {
      return 'desc';
    } else {
      return null;
    }
  };

  const eventDispatcher = createEventDispatcher();

  function triggerSort(): void {
    if (!sortable) return;

    eventDispatcher('sortEvent', {
      order: getNextSortOrder(),
      field: field,
    });
  }
</script>

<th on:click={triggerSort} class="select-none" class:hover:cursor-pointer={sortable}>
  {heading ? heading : ''}
  {#if order === 'asc' && sortable}
    <Icon src={ArrowSmallDown} mini class="w-6 h-6 inline" />
  {:else if order === 'desc' && sortable}
    <Icon src={ArrowSmallUp} mini class="w-6 h-6 inline" />
  {/if}
</th>
