<script setup lang="ts">
  const props = defineProps({
    name: {type: String, required: true},
    value: {type: String, required: true},
  });

  const emit = defineEmits(['update']);

  let edit: Ref<boolean> = ref<boolean>(false);
  let value: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.value)));

  function toggleEdit() {
    if (edit.value) {
      disableEdit();
    } else {
      enableEdit();
    }
  }

  function enableEdit() {
    edit.value = true;
  }

  function disableEdit() {
    value.value = JSON.parse(JSON.stringify(props.value));
    edit.value = false;
  }

  async function updateSetting() {
    if (value.value != null && value.value.trim().length > 0) {

      emit('update', props.name, value.value);

      disableEdit();
    }
  }
</script>

<template>
  <v-card>
    <v-card-title>
      <v-row style="padding-top: 10px">

        {{ props.name }}

        <v-spacer />

        <v-divider vertical/>

        <v-btn
            :flat="true"
            :disabled="!edit"
            :hidden="edit"
            @click="disableEdit()"
        >
          <v-icon>mdi-cancel</v-icon>
          <v-tooltip
              activator="parent"
              location="bottom"
          >
            Abbrechen
          </v-tooltip>
        </v-btn>

        <v-btn
            :flat="true"
            :disabled="!edit"
            :hidden="edit"
            @click="updateSetting()"
        >
          <v-icon>mdi-content-save</v-icon>
          <v-tooltip
              activator="parent"
              location="bottom"
          >
            Speichern
          </v-tooltip>
        </v-btn>

        <v-divider vertical/>

        <v-btn
            :flat="true"
            @click="toggleEdit();"
        >
          <v-icon>mdi-pencil</v-icon>
          <v-tooltip
              activator="parent"
              location="bottom"
          >
            Bearbeiten
          </v-tooltip>
        </v-btn>
      </v-row>
    </v-card-title>

    <v-divider/>

    <v-card-text>
      <v-text-field
          v-model.trim="value"
          :readonly="!edit"
      />
    </v-card-text>
  </v-card>
</template>

<style scoped>

</style>