<template>
  <DialogFrame
    ref="dialog"
    :header-title="newWorkspace ? $t('addNewWorkspace') : $t('edit') + ' ' + localWorkspace.name"
    :height="300"
    :width="600"
  >
    <div class="column">
      <div class="row justify-center">
        <q-input
          class="col-5 required"
          :label="$t('workspace')"
          filled
          :rules="[(val) => !!val || $t('workspaceIsRequired')]"
          v-model="localWorkspace.name"
          autofocus
        ></q-input>
      </div>
      <div class="row justify-center">
        <q-input
          dense
          class="col-5 required"
          :label="$t('description')"
          filled
          v-model="localWorkspace.description"
        ></q-input>
      </div>
    </div>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="save">{{ $t('save') }}</q-btn>
    </div>
  </DialogFrame>
</template>

<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import type { Workspace } from 'src/vueLib/models/workspaces';
import { useNotify } from 'src/vueLib/general/useNotify';
import { i18n } from 'src/boot/lang';
const { NotifyResponse } = useNotify();
const dialog = ref();
const newWorkspace = ref(false);
const localWorkspace = ref<Workspace>({
  name: '',
  description: '',
});

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

function open(workspace: Workspace | null) {
  if (workspace === undefined) {
    return;
  }

  if (workspace !== null) {
    localWorkspace.value = { ...workspace };
    localWorkspace.value.description = workspace.description;
    newWorkspace.value = false;
  } else {
    localWorkspace.value = {
      name: '',
      description: '',
    };
    newWorkspace.value = true;
  }

  dialog.value?.open();
}

async function save() {
  let query = 'workspaces/update?id=' + localWorkspace.value.id;
  let update = true;
  if (newWorkspace.value) {
    query = 'workspaces/add';
    update = false;
  }
  await appApi
    .post(query, JSON.stringify(localWorkspace.value))
    .then(() => {
      if (update) {
        NotifyResponse(
          i18n.global.t('workspace') +
            " '" +
            localWorkspace.value.name +
            "' " +
            i18n.global.t('updated'),
        );
      }
      emit('update');
      dialog.value.close();
    })
    .catch((err) => NotifyResponse(err, 'error'));
}

defineExpose({ open });
</script>

<style>
.required .q-field__label::after {
  content: ' *';
  color: red;
}
</style>
