import { Action, ApplicationContext, DataUnitLoaderUtils, StringUtils, } from '@sankhyalabs/core';
import { SaveErrorsEnum } from '../../../../../lib/http/data-fetcher/fetchers/AttachFetcher/interfaces';
import { AutorizationType } from '../../../../../lib/http/data-fetcher/fetchers/auth-fetcher';
import { attachFetcherMetadataBuilder } from '../../builder/attach-crud-config.builder';
import { VIEW_MODE } from '../../../../../lib/utils/constants';
const SERVICE_LOAD = "Attach.load";
export class AttachFetcherDataUnitFactory {
  constructor(getMessage) {
    this.getMessage = getMessage;
    this._records = [];
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  initLoaders(dataUnit, fetcher, onSuccess) {
    dataUnit.metadataLoader = (dataUnit) => this.metadataLoader(dataUnit);
    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(_) {
    return Promise.resolve(attachFetcherMetadataBuilder);
  }
  async dataLoader(dataUnit, request) {
    if (!request.source) {
      return Promise.resolve({ records: this._records });
    }
    if (!Number.isNaN(Number(request.source))) {
      const criteria = {
        criteria: {
          codata: request.source,
          tipoAnexo: "N"
        }
      };
      const applicationDataFetcher = await this._application.getDataFetcher();
      const { anexos: { anexo = [] } } = await applicationDataFetcher.callServiceBroker(SERVICE_LOAD, JSON.stringify(criteria));
      const records = [];
      anexo.forEach((param) => {
        records.push(Object.assign({ __record__id__: StringUtils.generateUUID(), CAMINHO_ARQUIVO: [{
              name: param === null || param === void 0 ? void 0 : param.ARQUIVO,
            }] }, param));
      });
      this._records = records;
    }
    return DataUnitLoaderUtils.buildLoadDataResponse(this._records, dataUnit, request);
  }
  saveLoader(changes, fetcher) {
    return new Promise((resolve) => {
      const change = Array.isArray(changes) ? changes[0] : {};
      fetcher.save(change)
        .then(resolve)
        .catch((error) => {
        if (error.message === SaveErrorsEnum.DESCRIPTION_CANNOT_BE_CHANGED) {
          this._application.alert(this.getMessage('snkAttach.alertValidation.descriptionCannotBeChanged.title'), this.getMessage('snkAttach.alertValidation.descriptionCannotBeChanged.message'));
          return resolve([]);
        }
        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) => {
      dataUnit.getSelectionInfo().records.forEach(async (record) => {
        this._application.hasAccess(AutorizationType.REMOVE)
          .then(async (hasAccess) => {
          if (hasAccess) {
            await fetcher.delete(record);
            resolve(ids);
          }
        });
      });
    });
  }
  getFilters() {
    throw new Error('Method not implemented.');
  }
  getInterceptions(dataUnit, action, crudRef) {
    return new Promise((resolve) => {
      var _a, _b, _c, _d, _e, _f;
      switch (action.type) {
        case 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);
          });
        case Action.DATA_SAVED:
          dataUnit.loadData(undefined, undefined, false, (_c = (_b = (_a = action === null || action === void 0 ? void 0 : action.payload) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.REGISTER_KEY);
          return resolve(action);
        case Action.RECORDS_REMOVED:
          dataUnit.loadData(undefined, undefined, false, (_f = (_e = (_d = action === null || action === void 0 ? void 0 : action.payload) === null || _d === void 0 ? void 0 : _d.cachedRecords) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.CODATA);
          return resolve(action);
      }
      resolve(action);
    });
  }
}
