<template>
  <q-dialog class="full-width" @hide="$emit('hide')" v-model="model">
    <q-card class="no-shadow full-width">
      <q-card-section>
        <div class="text-h6">
          {{ $t('file.actions.attach') }}
        </div>
        <span v-if="subTitle">
          {{ subTitle }}
        </span>
      </q-card-section>
      <q-card-section>
        <q-file
          filled
          accept=".bpmn"
          v-model="attachFile"
          :label="$t('file.actions.upload')"
          lazy-rules
          :rules="[validateFileName]"
          :error-message="
            attachFile
              ? $t('processes.validationErrors.errorFileName')
              : $t('processes.validationErrors.errorFileRequired')
          "
        />
      </q-card-section>
      <q-card-actions align="right">
        <q-btn
          @click="save"
          color="primary"
          :loading="loading"
          :label="$t('base.actions.upload')"
        />
        <q-btn
          color="white"
          text-color="primary"
          outline
          @click="model = false"
          :label="$t('base.actions.cancel')"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script lang="js">
import { notifyError, notifySuccess } from '@utils/notify';
  
export default {
  props: ['value', 'file', 'subTitle', 'schemaName', 'loading'],
  data() {
    return {
      model: this.value,
      attachFile: this.file,
    }
  },
  methods: {
    save() {
      if (!this.attachFile) {
        notifyError(
          this.$t('processes.validationErrors.errorFileRequired').toString()
        );
        return;
      }
      if (!this.validateFileName(this.attachFile)) {
        notifySuccess(
          this.$t('processes.validationErrors.errorFileName').toString()
        );
        return;
      }
      this.$emit('updateDocumentAttachment', this.attachFile);
    },
    validateFileName(value) {
      if (typeof value === 'string') {
        return value.trim() !== ''
      } else if (value instanceof File) {
        return value.name.trim() !== ''
      }
      return true;
    },
  }
}
</script>
