import { Action, ApplicationContext, DataType } from "@sankhyalabs/core";
import { SaveErrorsEnum } from "../../../../../lib/http/data-fetcher/fetchers/AttachFetcher/interfaces";
import { VIEW_MODE } from "../../../../../lib/utils/constants";
import PreloadManager from '../../../../../lib/http/data-fetcher/fetchers/data-unit/cache/PreloadManager';
export class AnexoSistemaDataUnitFactory {
  constructor(entityName, getMessage) {
    this.entityName = entityName;
    this.getMessage = getMessage;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  initLoaders(dataUnit, fetcher, onSuccess) {
    if (!this.loader)
      this.loader = dataUnit.dataLoader;
    dataUnit.dataLoader = (dataUnit, request) => this.dataLoader(dataUnit, request);
    dataUnit.saveLoader = (_, changes) => this.saveLoader(changes, fetcher).then((recordIds) => {
      if (recordIds.length)
        onSuccess();
      return recordIds;
    });
    dataUnit.removeLoader = (dataUnit, ids) => this.removeLoader(dataUnit, ids, fetcher).then((recordIds) => {
      if (recordIds.length)
        onSuccess();
      return recordIds;
    });
  }
  metadataLoader(dataUnit) {
    throw new Error("Method not implemented.");
  }
  dataLoader(dataUnit, request) {
    return new Promise(resolve => {
      this.loader(dataUnit, request).then(response => {
        const records = ((response === null || response === void 0 ? void 0 : response.records) || []).map(record => {
          let fileInfo;
          if (!record.LINK)
            fileInfo = [{
                name: record.NOMEARQUIVO,
              }];
          return Object.assign(Object.assign({}, record), { ARQUIVOOULINK: !!record.LINK ? record.LINK : record.NOMEARQUIVO, NOMEARQUIVO: fileInfo });
        });
        resolve(Object.assign(Object.assign({}, response), { records }));
      });
    });
  }
  saveLoader(changes, fetcher) {
    return new Promise((resolve) => {
      var _a;
      const change = Array.isArray(changes) ? changes[0] : {};
      const savePromise = ((_a = change === null || change === void 0 ? void 0 : change.record) === null || _a === void 0 ? void 0 : _a.NUATTACH) >= 0 ? fetcher.edit.bind(fetcher) : fetcher.save.bind(fetcher);
      savePromise(change).then((records) => {
        resolve(records);
      }).catch((error) => {
        if (error.message === SaveErrorsEnum.LINK_AND_FILE_AT_THE_SAME_TIME) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.title'), this.getMessage('snkAttach.alertValidation.fileAndLinkAtTheSameTime.message'));
          return resolve([]);
        }
        if (error.message === SaveErrorsEnum.ANY_LINK_OR_FILE_FILLED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.title'), this.getMessage('snkAttach.alertValidation.anyLinkOrFileFilled.message'));
          return resolve([]);
        }
        if (error.message) {
          this._application.error((error.title || error.name), error.message);
          return resolve([]);
        }
        resolve([]);
      });
    });
  }
  removeLoader(dataUnit, ids, fetcher) {
    return new Promise((resolve) => {
      const { records } = dataUnit.getSelectionInfo();
      const recordToDelete = records[0];
      fetcher.delete(recordToDelete).then(() => {
        PreloadManager.removeRecords(dataUnit, [recordToDelete]);
        return resolve(ids);
      });
    });
  }
  getFilters(registerKey) {
    return [
      {
        name: 'AttachmentsByPK',
        expression: 'this.PKREGISTRO = :PKREGISTRO',
        params: [{
            name: "PKREGISTRO",
            dataType: DataType.TEXT,
            value: `${registerKey}_${this.entityName}`
          }]
      }
    ];
  }
  getInterceptions(dataUnit, action, crudRef) {
    return new Promise((resolve) => {
      if (action.type === Action.EDITION_CANCELED) {
        if (!dataUnit.isDirty())
          return resolve(action);
        return this._application.confirm(this.getMessage('snkAttach.cancelConfirmation.title'), this.getMessage('snkAttach.cancelConfirmation.message')).then((cancellationConfirmed) => {
          if (cancellationConfirmed) {
            crudRef.goToView(VIEW_MODE.GRID);
            return resolve(action);
          }
          return resolve(undefined);
        });
      }
      if (action.type === Action.DATA_SAVED) {
        dataUnit.loadData();
        return resolve(action);
      }
      resolve(action);
    });
  }
}
