<script lang="ts">
  import api from "../lib/api";
  import { ATTR_IN } from "@upnd/upend/constants";
  import { createEventDispatcher } from "svelte";
  import type { UpObject } from "@upnd/upend";
  import type { Readable } from "svelte/store";
  import EntitySetEditor from "./EntitySetEditor.svelte";
  const dispatch = createEventDispatcher();

  export let entity: Readable<UpObject>;

  $: groups = Object.fromEntries(
    ($entity?.attr[ATTR_IN] || []).map((e) => [e.value.c as string, e.address]),
  );

  async function addGroup(address: string) {
    await api.putEntry([
      {
        entity: $entity.address,
        attribute: ATTR_IN,
        value: {
          t: "Address",
          c: address,
        },
      },
    ]);
    dispatch("change");
  }

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

<EntitySetEditor
  entities={Object.keys(groups)}
  hide={Object.keys(groups).length === 0}
  on:add={(e) => addGroup(e.detail)}
  on:remove={(e) => removeGroup(e.detail)}
  on:highlighted
/>
