<script lang="ts">
  import { GetEmployees } from "../wailsjs/go/main/App.js";

  export let path: string;
  export let page: number;
  let limit: number = 10;
  export let limitReached: boolean;

  let _column: string | null = null;
  let _query: string | null = null;
  let column: string | null = null;
  let query: string | null = null;

  async function listEmployees(
    path: string,
    limit: number,
    page: number,
    column?: string,
    query?: string,
  ) {
    try {
      const employees = await GetEmployees(path, limit, page, column, query);
      limitReached = employees.length < limit;
      return employees;
    } catch (error) {
      throw error.message;
    }
  }
</script>

<section>
  {#await listEmployees(path, limit, page, column, query)}
    <p>Loading...</p>
  {:then employees}
    <div>
      <select
        name="query"
        on:change={({ currentTarget }) => (_column = currentTarget.value)}
      >
        {#each Object.keys(employees[0]) as key}
          <option value={key}>{key}</option>
        {/each}
      </select>
      <input placeholder="Query" type="text" bind:value={_query} />
      <button
        type="button"
        on:click={() => {
          page = 0;
          column = _column;
          query = _query;
        }}>Search</button
      >
      <button type="button" on:click={() => {
        query = ""
        column = null
        page = 0
      }}>Reset</button>
    </div>
    <table>
      <tr>
        {#each Object.keys(employees[0]) as key}
          <th>{key}</th>
        {/each}
      </tr>
      {#each employees as employee}
        <tr>
          {#each Object.values(employee) as value}
            <td>{value}</td>
          {/each}
        </tr>
      {/each}
    </table>
  {:catch error}
    <p>{error}</p>
  {/await}
</section>

<style>
  table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
  }

  th,
  td {
    border: 1px solid #ddd;
    padding: 12px;
    text-align: left;
  }

  th {
    background-color: #000000;
  }

  tr:nth-child(even) {
    background-color: #343434;
  }

  tr:hover {
    background-color: #110909;
  }
</style>
