<script lang="ts">
  import Modal from "./Modal.svelte";
  import { AggregateByColumn } from "../wailsjs/go/main/App.js";
  export let isOpen: boolean;
  export let keys: string[];

  let group: string | null = null;
  let onColumn: string | null = null;
  let func: string | null = null;

  let promise: ReturnType<typeof AggregateByColumn>;

  async function Aggregate() {
    if (!group || !onColumn || !func) return;
    try {
      const res = await AggregateByColumn(group, onColumn, func);
      return res;
    } catch (error) {
      throw error.message;
    }
  }
</script>

<Modal
  {isOpen}
  onClose={() => {
    isOpen = false;
  }}
>
  <section>
    <p>Aggregation</p>
    <div>
      <label for="group">Group by: </label>
      <select bind:value={group} name="group" id="">
        {#each keys as key}
          <option value={key}>{key}</option>
        {/each}
      </select>
    </div>
    <div>
      <label for="on-column">On: </label>
      <select bind:value={onColumn} name="on-column" id="">
        {#each keys as key}
          <option value={key}>{key}</option>
        {/each}
      </select>
      <label for="function">Using: </label>
      <select bind:value={func} name="function" id="">
        <option value="AVG">Average</option>
        <option value="SUM">SUM</option>
      </select>
    </div>
    <button type="button" on:click={() => (promise = Aggregate())}
      >Aggregate</button
    >
  </section>
  {#if promise}
    <section>
      {#await promise}
        <p>Loading...</p>
      {:then res}
        <table class="agg-table">
          <tr>
            <th>{group}</th>
            <th>{func} of {onColumn}</th>
          </tr>
          {#each Object.entries(res) as [key, value]}
            <tr>
              <td>{key}</td>
              <td>{value}</td>
            </tr>
          {/each}
        </table>
      {:catch error}
        <p>{error}</p>
      {/await}
    </section>
  {/if}
</Modal>

<style>

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

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

  th {
    background-color: #FFFFFF;
  }

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

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