<template>
  <div class="attribute-view">
    <component
      v-for="component in components"
      :key="component.id"
      :is="component.name"
      v-bind="component.props"
      :attributes="attributes"
      :insertable="insertable"
      @edit="processChange"
    />
  </div>
</template>

<script lang="ts">
import Compass from "@/components/widgets/Compass.vue";
import Table from "@/components/widgets/Table.vue";
import { UpType } from "@/lib/types";
import { AttributeChange, IEntry } from "@/types/base";
import { ComponentOptions, defineComponent, PropType } from "vue";

export default defineComponent({
  name: "AttributeView",
  components: {
    Table,
    Compass,
  },
  emits: ["edit"],
  props: {
    address: {
      type: String,
      required: true,
    },
    type: {
      type: Object as PropType<UpType>,
    },
    attributes: {
      type: Array as PropType<[string, IEntry][]>,
      required: true,
    },
    insertable: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    components(): ComponentOptions[] {
      return (
        this.type?.widgetInfo || [
          {
            name: "Table",
          },
        ]
      );
    },
  },
  methods: {
    async processChange(change: AttributeChange) {
      switch (change.type) {
        case "create":
          await fetch(`/api/obj`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              entity: this.address,
              attribute: change.attribute,
              value: {
                t: "Value",
                c: change.value,
              },
            }),
          });
          break;
        case "delete":
          await fetch(`/api/obj/${change.addr}`, { method: "DELETE" });
          break;
        default:
          console.error(`Unimplemented: ${JSON.stringify(change)}`);
      }
      this.$emit("edit");
    },
  },
});
</script>

<style scoped lang="scss">
</style>
