import {WFAPIResponse, WorkflowServiceApi} from '@openapi/wf';
import { AxiosPromise } from 'axios';
import { Notify } from 'quasar';
import { i18n } from '@plugins/i18n';

const wfApi = new WorkflowServiceApi();

function uploadDMN(file?: any): AxiosPromise<WFAPIResponse> {
  return new Promise((resolve, reject) => {
    wfApi
      .load(file)
      .then(() => {
        Notify.create({
          message: i18n.t('mFileLoader.success').toString(),
          color: 'info',
        });
        return resolve();
      })
      .catch((e) => {
        Notify.create({
          message: i18n.t('mFileLoader.error').toString(),
          color: 'warning',
        });
        return reject(e);
      });
  });
}

function uploadBPMN(file?: any): AxiosPromise<WFAPIResponse> {
  return new Promise((resolve, reject) => {
    wfApi
      .loadSchema(file)
      .then(() => {
        Notify.create({
          message: i18n.t('mFileLoader.success').toString(),
          color: 'info',
        });
        return resolve();
      })
      .catch((e) => {
        Notify.create({
          message: i18n.t('mFileLoader.error').toString(),
          color: 'warning',
        });
        return reject(e);
      });
  });
}

function startWithFiles(
  data: StartWithFilesParams
): AxiosPromise<WFAPIResponse> {
  return wfApi.startWithFiles(
    undefined,
    undefined,
    undefined,
    data.file,
    undefined,
    JSON.stringify(data.json)
  );
}

export { uploadDMN, uploadBPMN, startWithFiles };

interface StartWithFilesParams {
  file: File | undefined;
  json: unknown;
}
