<script lang="ts">
  import AttributeView from "./AttributeView.svelte";
  import { query, useEntity } from "../lib/entity";
  import Address from "./Address.svelte";
  import { UpType } from "../lib/types";
  import type { IEntry } from "upend/types";
  import BlobPreview from "./BlobPreview.svelte";
  import { setContext } from "svelte";
  import { writable } from "svelte/store";

  export let address: string;
  export let index: number | undefined;
  export let editable = false;

  let indexStore = writable(index);
  $: $indexStore = index;

  setContext("browse", { index: indexStore });

  const { error, revalidate, attributes, backlinks } = useEntity(address);

  $: allTypeAddresses = $attributes
    .map(([_, attr]) => attr)
    .filter((attr) => attr.attribute == "IS")
    .map((attr) => attr.value.c);

  $: allTypeEntries = query(
    () =>
      `(matches (in ${allTypeAddresses
        .map((addr) => `"${addr}"`)
        .join(" ")}) ? ?)`
  ).result;

  let allTypes: { [key: string]: UpType } = {};
  $: {
    allTypes = {};
    $allTypeEntries.forEach(([_, entry]) => {
      if (allTypes[entry.entity] === undefined) {
        allTypes[entry.entity] = new UpType(entry.entity);
      }

      switch (entry.attribute) {
        case "TYPE":
          allTypes[entry.entity].name = entry.value.c;
          break;
        case "TYPE_HAS":
        case "TYPE_REQUIRES":
        case "TYPE_ID":
          allTypes[entry.entity].attributes.push(entry.value.c);
          break;
      }
    });

    allTypes = allTypes;
  }

  let typedAttributes = {} as { [key: string]: [string, IEntry][] };
  let untypedAttributes = [] as [string, IEntry][];

  $: {
    typedAttributes = {};
    untypedAttributes = [];

    $attributes.forEach(([entryAddr, entry]) => {
      const entryTypes = Object.entries(allTypes).filter(([_, t]) =>
        t.attributes.includes(entry.attribute)
      );
      if (entryTypes.length > 0) {
        entryTypes.forEach(([addr, _]) => {
          if (typedAttributes[addr] == undefined) {
            typedAttributes[addr] = [];
          }
          typedAttributes[addr].push([entryAddr, entry]);
        });
      } else {
        untypedAttributes.push([entryAddr, entry]);
      }
    });

    typedAttributes = typedAttributes;
    untypedAttributes = untypedAttributes;
  }

  $: filteredUntypedAttributes = untypedAttributes.filter(
    ([_, entry]) =>
      entry.attribute !== "IS" ||
      !Object.keys(typedAttributes).includes(entry.value.c)
  );
</script>

<div class="inspect">
  <h2>
    <Address banner {address} />
  </h2>
  <BlobPreview {address} />
  {#if !$error}
    <div class="attributes">
      {#each Object.entries(typedAttributes) as [typeAddr, attributes] (typeAddr)}
        <AttributeView
          {editable}
          {address}
          type={allTypes[typeAddr]}
          {attributes}
          on:changed={revalidate}
        />
      {/each}
      {#if filteredUntypedAttributes.length > 0 || editable}
        <AttributeView
          title="Other attributes"
          {editable}
          {address}
          attributes={untypedAttributes}
          on:changed={revalidate}
        />
      {/if}
      {#if $backlinks.length > 0}
        <AttributeView
          title={`Referred to (${$backlinks.length})`}
          {address}
          attributes={$backlinks}
          reverse
          on:changed={revalidate}
        />
      {/if}
    </div>
  {:else}
    <div class="error">
      {JSON.stringify($error)}
    </div>
  {/if}
</div>

<style scoped lang="scss">
  .inspect {
    flex: auto;
    display: flex;
    flex-direction: column;
    & > * {
      padding: 0 1rem;
    }
  }

  .attributes {
    flex: auto;
    height: 0; // https://stackoverflow.com/a/14964944
    overflow-y: auto;
  }

  .error {
    color: red;
  }
</style>
