<script lang="ts">
  import UpObject from "./display/UpObject.svelte";
  import Selector from "./utils/Selector.svelte";
  import IconButton from "./utils/IconButton.svelte";
  import type { IValue } from "upend/types";
  import api from "../lib/api";
  import { ATTR_IN } from "upend/constants";
  import { createEventDispatcher } from "svelte";
  import { i18n } from "../i18n";
  const dispatch = createEventDispatcher();

  export let address: string;
  export let groups: [string, string][];
  export let editable = false;

  let groupToAdd: IValue | undefined;
  async function addGroup() {
    if (!groupToAdd) {
      return;
    }
    await api.putEntry([
      {
        entity: address,
        attribute: ATTR_IN,
        value: {
          t: "Address",
          c: String(groupToAdd.c),
        },
      },
    ]);
    dispatch("change");
    groupToAdd = undefined;
  }

  async function removeGroup(groupAddress: string) {
    await api.deleteEntry(groupAddress);
    dispatch("change");
  }
</script>

<section class="groups labelborder">
  <header><h3>{$i18n.t("Groups")}</h3></header>
  <div class="content">
    {#each groups as [groupAddress, groupEntryAddress]}
      <div
        class="tag"
        on:mouseenter={() => dispatch("highlighted", groupAddress)}
        on:mouseleave={() => dispatch("highlighted", undefined)}
      >
        <UpObject address={groupAddress} link />
        {#if editable}
          <IconButton
            name="x-circle"
            on:click={() => removeGroup(groupEntryAddress)}
          />
        {/if}
      </div>
    {/each}
    {#if editable}
      <div class="selector">
        <Selector
          type="value"
          valueTypes={["Address"]}
          bind:value={groupToAdd}
          on:input={addGroup}
          placeholder="Choose an entity..."
        />
      </div>
    {/if}
  </div>
</section>

<style lang="scss">
  @use "./util";

  .groups {
    margin: 0.25rem 0;
    .content {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem 0.5rem;
      align-items: center;
    }

    .tag {
      display: inline-flex;
      align-items: center;
    }

    .selector {
      width: 100%;
    }
  }
</style>
