<script setup lang="ts">
  import {useLabelEditorStore} from "~/store/labelEditorStore";
  import type {Ref} from "vue";
  import {Label} from "~/types/label";

  let store = useLabelEditorStore();
  let dialog: Ref<boolean> = ref<boolean>(false);
  let loading: Ref<boolean> = ref<boolean>(false);

  let name: Ref<string | null> = ref<string | null>(null);

  watch(dialog, async (oldDialog) => {
    if (oldDialog) {
      loading.value = true;

      await store.loadLabels();

      loading.value = false;
    }
  })

  async function create() {
    if (name.value != null && name.value.trim().length > 0){
      const label = new Label(0, name.value);
      await store.createLabel(label);

      closeDialog();
    }
  }

  function closeDialog() {
    dialog.value = false;
    clearVariables();
  }

  function clearVariables() {
    name.value = null;

    loading.value = false;
  }

</script>

<template>
  <v-dialog
      v-model="dialog"
      :scrollable="true"
      width="800"
      max-height="750"
  >
    <template v-slot:activator="{ props }">
      <v-btn
          :flat="true"
          v-bind="props"
          size="small"
      >
        <v-icon>mdi-plus-thick</v-icon>
        <v-tooltip
            activator="parent"
            location="bottom"
        >
          Etiketten Typ erstellen
        </v-tooltip>
      </v-btn>
    </template>

    <v-card>
      <v-card-title>
        <v-icon size="small">
          mdi-plus-thick
        </v-icon>

        Etiketten Typ erstellen

        <v-progress-circular v-if="loading" indeterminate :size="15" :width="2"></v-progress-circular>
      </v-card-title>

      <v-divider/>

      <v-card-text>
        <v-text-field
            v-model.trim="name"
            label="Bezeichnung"
            autofocus
        />
      </v-card-text>

      <v-divider/>

      <v-card-actions>
        <v-spacer/>
        <v-btn
            variant="text"
            :disabled="loading"
            @click="closeDialog()"
        >
          Schließen
        </v-btn>

        <v-btn
            variant="text"
            :disabled="name == null || loading"
            @click="create();"
        >
          Erstellen
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped>

</style>