<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="schemaName === 'Process' ? '.bpmn' : '.dmn'"
          v-model="_file"
          :label="$t('file.actions.upload')"
          lazy-rules
          :rules="[validateFileName]"
          :error-message="
            _file
              ? $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="ts">
import { Component, PropSync, Vue, Prop } from 'vue-property-decorator';
import { notifyError, notifySuccess } from '@utils/notify';

@Component({})
export default class ProcessFileUploadDialog extends Vue {
  @PropSync('value', { type: Boolean }) model: boolean;
  @PropSync('file', { type: File }) _file: File | null;
  @Prop() subTitle!: string;
  @Prop() schemaName!: string;
  @Prop() loading!: boolean;

  save(): void {
    if (!this._file) {
      notifyError(
        this.$t('processes.validationErrors.errorFileRequired').toString()
      );
      return;
    }
    if (!this.validateFileName(this._file)) {
      notifySuccess(
        this.$t('processes.validationErrors.errorFileName').toString()
      );
      return;
    }
    this.$emit('updateDocumentAttachment');
  }

  validateFileName(value: string | File): boolean {
    if (typeof value === 'string') {
      return value === value.match(/^[а-яёЁА-Я\w.]+$/)?.[0];
    } else if (value instanceof File) {
      return value.name === value.name.match(/^[а-яёЁА-Я\w.]+$/)?.[0];
    }
    return true;
  }

  private beforeDestroy() {
    this._file = null;
  }
}
</script>
