<template>
  <div class="flex flex-row gap-2 items-center w-full">
    <select v-model="column" class="w-full">
      <option value="" disabled>Spalte auswählen</option>
      <option v-for="column in selectableColumns" :value="column">
        {{ column }}
      </option>
    </select>
    <select v-model="order">
      <option value="" disabled>Sortierung auswählen</option>
      <option v-for="order in ['ASC', 'DESC']" :value="order">
        {{ order }}
      </option>
    </select>
    <div class="p-1 border border-gray-400 hover:bg-gray-200 rounded-md" @click="$emit('remove')">
      <TrashIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { mapActions, mapState } from "pinia";
import type { OrderByStructure, OrderByType } from "@/types/dynamicQueries";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import { TrashIcon } from "@heroicons/vue/24/outline";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    table: {
      type: String,
      default: "",
    },
    columns: {
      type: [Array, String] as PropType<"*" | Array<string>>,
      default: "*",
    },
    modelValue: {
      type: Object as PropType<OrderByStructure>,
      default: {},
    },
  },
  emits: ["update:model-value", "remove"],
  data() {
    return {};
  },
  computed: {
    ...mapState(useQueryBuilderStore, ["tableMetas"]),
    selectableColumns() {
      if (this.columns == "*") {
        let meta = this.tableMetas.find((tm) => tm.tableName == this.table);
        if (!meta) return [];
        let relCols = meta.relations.map((r) => r.column);
        return meta.columns.map((c) => c.column).filter((c) => !relCols.includes(c));
      } else {
        return this.columns;
      }
    },
    column: {
      get() {
        return this.modelValue.column;
      },
      set(val: string) {
        this.$emit("update:model-value", { ...this.modelValue, column: val });
      },
    },
    order: {
      get() {
        return this.modelValue.order;
      },
      set(val: OrderByType) {
        this.$emit("update:model-value", { ...this.modelValue, order: val });
      },
    },
  },
});
</script>
