import { SaveErrorsEnum } from "./interfaces";
import { DataFetcher } from "../../DataFetcher";
const SERVICE = {
  save: "AnexoSistemaSP.salvar",
  delete: "AnexoSistemaSP.excluir",
  download: "AnexoSistemaSP.baixar",
};
export class AnexoSistemaFetcher {
  constructor(entityName, dataUnitName) {
    var _a;
    this.entityName = entityName;
    this.dataUnitName = dataUnitName;
    this.validateFields = (fields) => {
      if (!!fields.LINK && !!fields.NOMEARQUIVO)
        throw new Error(SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME);
      if (!fields.LINK && !fields.NOMEARQUIVO)
        throw new Error(SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED);
      if (!this._registerKey)
        throw new Error('Register key can not be null');
    };
    this.resourceID = (window["resourceID"] || ((_a = window["workspace"]) === null || _a === void 0 ? void 0 : _a.resourceID));
  }
  set registerKey(registerKey) {
    this._registerKey = registerKey;
  }
  async save(change) {
    var _a, _b;
    let { updatingFields: fields } = change;
    fields = Object.assign(Object.assign({}, fields), { NOMEARQUIVO: (_a = fields.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0] });
    try {
      this.validateFields(fields);
      const fileInfo = !fields.LINK ? fields.NOMEARQUIVO : null;
      const reqBody = {
        serviceName: SERVICE.save,
        requestBody: {
          params: {
            resourceID: this.resourceID,
            description: fields.DESCRICAO,
            fileSelect: fileInfo ? 1 : 0,
            keySession: (_b = fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.properties) === null || _b === void 0 ? void 0 : _b.fileNameTmp,
            nameAttach: fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name,
            link: fields.LINK,
            nameEntity: this.entityName,
            pkEntity: this._registerKey,
            typeAcess: fields.TIPOACESSO,
            typeApres: fields.TIPOAPRES,
          }
        }
      };
      const result = await DataFetcher.get().callServiceBroker(SERVICE.save, JSON.stringify(reqBody));
      return Promise.resolve([Object.assign(Object.assign(Object.assign({}, result), fields), { ARQUIVOOULINK: !!fields.LINK ? fields.LINK : fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name, __owner__dataunit__name__: this.dataUnitName })]);
    }
    catch (error) {
      return Promise.reject(error);
    }
  }
  async edit(change) {
    var _a, _b, _c;
    let { updatingFields: fields, record } = change;
    const getFieldValue = (fieldValue) => {
      if (fields[fieldValue] !== undefined)
        return fields[fieldValue];
      return record[fieldValue];
    };
    const attachField = getFieldValue('NOMEARQUIVO');
    const hasNewAttachment = (_b = (_a = fields.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.downloadURL;
    fields = Object.assign(Object.assign({}, fields), { DESCRICAO: getFieldValue('DESCRICAO'), LINK: getFieldValue('LINK'), TIPOACESSO: getFieldValue('TIPOACESSO'), TIPOAPRES: getFieldValue('TIPOAPRES'), CHAVEARQUIVO: record.CHAVEARQUIVO, NOMEARQUIVO: attachField === null || attachField === void 0 ? void 0 : attachField[0] });
    const fileInfo = !fields.LINK ? fields.NOMEARQUIVO : null;
    try {
      this.validateFields(fields);
      const reqBody = {
        serviceName: SERVICE.save,
        requestBody: {
          params: {
            resourceID: this.resourceID,
            nuAttach: record === null || record === void 0 ? void 0 : record.NUATTACH,
            description: fields.DESCRICAO,
            fileSelect: hasNewAttachment ? 1 : 0,
            keySession: (_c = fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.properties) === null || _c === void 0 ? void 0 : _c.fileNameTmp,
            keyAttach: fields.CHAVEARQUIVO,
            nameAttach: fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name,
            link: fields.LINK,
            nameEntity: this.entityName,
            pkEntity: this._registerKey,
            typeAcess: fields.TIPOACESSO,
            typeApres: fields.TIPOAPRES,
          }
        }
      };
      const result = await DataFetcher.get().callServiceBroker(SERVICE.save, JSON.stringify(reqBody));
      return Promise.resolve([Object.assign(Object.assign(Object.assign({}, result), fields), { ARQUIVOOULINK: !!fields.LINK ? fields.LINK : fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.name, __owner__dataunit__name__: this.dataUnitName })]);
    }
    catch (error) {
      return Promise.reject(error);
    }
  }
  delete(record) {
    var _a;
    const attachField = ((_a = record.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) || {};
    const reqBody = {
      serviceName: SERVICE.delete,
      requestBody: {
        paramsDelete: {
          keyAttach: record.CHAVEARQUIVO,
          nameAttach: attachField === null || attachField === void 0 ? void 0 : attachField.name,
          nameEntity: record.NOMEINSTANCIA,
          nuAttach: record.NUATTACH,
          pkEntity: record.PKREGISTRO
        }
      }
    };
    return new Promise((resolve, reject) => {
      DataFetcher.get().callServiceBroker(SERVICE.delete, JSON.stringify(reqBody))
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }
  getDownloadKey(record) {
    var _a;
    const attachField = ((_a = record.NOMEARQUIVO) === null || _a === void 0 ? void 0 : _a[0]) || {};
    const reqBody = {
      serviceName: SERVICE.download,
      requestBody: {
        paramsDown: {
          nameAttach: attachField === null || attachField === void 0 ? void 0 : attachField.name,
          nameEntity: record.NOMEINSTANCIA,
          nuAttach: record.NUATTACH,
          pkEntity: record.PKREGISTRO,
          keyAttach: record.CHAVEARQUIVO,
        }
      }
    };
    return new Promise((resolve, reject) => {
      DataFetcher.get().callServiceBroker(SERVICE.download, JSON.stringify(reqBody))
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }
}
