<template>
  <q-dialog v-model="open" :persistent="saving">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-form ref="correctionsForm" @submit="confirmSaveRegistry">
        <registry-form ref="registryForm" :formModel.sync="model" />
        <q-card-actions align="right">
          <q-btn
            type="button"
            color="primary"
            :label="$t('registries.objectCard.cancel')"
            @click="cancelSave"
          />
          <q-btn
            type="submit"
            icon="create"
            :loading="saving"
            label="сохранить"
            color="primary"
          >
            <template #loading>
              <q-spinner-gears />
            </template>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { Component, PropSync, Ref, Vue } from 'vue-property-decorator';
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';
import RegistryForm from '@components/registries/registry-form.vue';
import { RegistryWithForm } from '@models/RegistryWithForm';

@Component({
  components: {
    FormGeneratorWrapper,
    RegistryForm,
  },
})
export default class RegistryFormDialog extends Vue {
  @PropSync('registryDialog') open: boolean;
  @PropSync('formModel') model: RegistryWithForm | null;

  @Ref('registryForm') registryForm: RegistryForm;

  saving = false;

  confirmSaveRegistry(): void {
    this.$q
      .dialog({
        title: this.$t('registries.objectCard.save') as string,
        message: this.$t('registries.objectCard.saveInfo') as string,
        cancel: true,
      })
      .onOk(() => {
        this.saveRegistry();
      });
  }

  cancelSave(): void {
    this.open = false;
    this.model = null;
  }

  async saveRegistry(): Promise<void> {
    await this.registryForm.saveRegistry();

    this.open = false;
    this.saving = false;
    setTimeout(() => {
      this.$emit('created');
    }, 1000);
  }
}
</script>
