import { Component, Vue } from 'vue-property-decorator';
import MFileLoader from '@components/m-file-loader/index.vue';
import VueI18n from 'vue-i18n';
import { uploadDMN, uploadBPMN } from '@services/wf';
import { notifyError } from '@utils/notify';

@Component({
  components: {
    MFileLoader,
  },
})
export default class UserTasksUploadComponent extends Vue {
  private dialog = false;
  private loading = false;
  private errorMessage: VueI18n.TranslateResult = '';

  private uploaderHandler(): void {
    this.dialog = true;
  }

  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;
  }

  validateFileNames(files: File[]): boolean {
    return files.every((file) => {
      if (!file) {
        this.errorMessage = this.$t(
          'processes.validationErrors.errorFileRequired'
        );
        return false;
      }
      if (!this.validateFileName(file)) {
        this.errorMessage = this.$t('processes.validationErrors.errorFileName');
        return false;
      }
      const extension = file.name.split('.').pop();
      if (extension !== 'bpmn' && extension !== 'dmn') {
        this.errorMessage = this.$t(
          'processes.validationErrors.errorFileExtension'
        );
        return false;
      }
      this.errorMessage = '';
      return true;
    });
  }

  private async sendFiles(files: File[]) {
    this.validateFileNames(files);
    if (this.errorMessage) {
      notifyError(this.errorMessage.toString());
      return;
    }
    this.loading = true;
    try {
      for (const file in files) {
        const extension = files[file].name.split('.').pop();

        switch (extension) {
          case 'bpmn':
            await uploadBPMN(files[file]);
            break;
          case 'dmn':
            await uploadDMN(files[file]);
            break;
        }
      }
    } catch (e) {
      console.error('[UserTasksUploadComponent][sendFiles] failed');
    }
    this.loading = false;
  }
}
