<template>
  <div class="inspect">
    <h2>
      <Address :address="address" :is-file="backlinks.some((e) => e.key === 'FILE_IS')"/>
    </h2>
    <div v-if="!error">
      <template v-if="attributes.length">
      <h3>Own attributes ({{ attributes.length }})</h3>
      <table>
        <tr>
          <th>Key name</th>
          <th>Value</th>
        </tr>
        <tr v-for="entry in attributes">
          <td>{{ entry.key }}</td>
          <td>
            <Address link v-if="entry.value[0] === 'ADDR'" :address="entry.value[1]"/>
            <template v-else>
            {{ entry.value[1] }}
            </template>
          </td>
        </tr>
      </table>
      </template>
      <template v-if="backlinks.length">
      <h3>Referred to ({{ backlinks.length }})</h3>
      <table>
        <tr>
          <th>Targets</th>
          <th>Key names</th>
        </tr>
        <tr v-for="entry in backlinks">
          <td>
            <Address link :address="entry.target"/>
          </td>
          <td>
            {{ entry.key }}
          </td>
        </tr>
      </table>
      </template>
    </div>
    <div v-else class="error">
      {{ error }}
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";
import useSWRV from "swrv";
import {fetcher} from "@/utils";
import {IEntry, ListingResult} from "@/types/base";
import Address from "@/components/Address.vue";

export default defineComponent({
  name: "Inspect",
  components: {
    Address,
  },
  props: {
    "address": String
  },
  data: () => {
    return {};
  },
  computed: {
    objectEntries(): IEntry[] {
      if (this.data) {
        const entries = Object.values(this.data) as IEntry[];
        return entries
          .sort((a, b) => a.value[1].localeCompare(b.value[1]))
          .sort((a, b) => a.value[0].localeCompare(b.value[0]))
          .sort((a, b) => a.key.localeCompare(b.key));
      } else {
        return [];
      }
    },
    attributes(): IEntry[] {
      return this.objectEntries.filter((e) => e.target === this.address);
    },
    backlinks(): IEntry[] {
      return this.objectEntries.filter((e) => e.target !== this.address);
    }
  },
  setup(props) {
    const {data, error} = useSWRV<ListingResult, unknown>(() => `/api/get/${props.address}`, fetcher);

    return {
      data,
      error,
    };
  }
});
</script>

<style scoped lang="scss">
table {
  th {
    text-align: left;
  }

  td {
    font-family: var(--monospace-font);
    padding-right: 1em;
  }
}

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