import { ArrayUtils, ElementIDUtils, SearchUtils } from "@sankhyalabs/core";
import { ObjectUtils } from "@sankhyalabs/core";
import { StringUtils } from "@sankhyalabs/core";
const QTD_DETAIL_FIELDS_PREDICTIVE_SEARCH = 6;
const INVALID_CONTENT_PATTERNS = ['<img', '<svg'];
const executePreparedSearchPlus = async (mode, argument, options, app, pesquisaFetcher) => {
  var _a;
  const mdByName = {};
  const { entity, entityDescription, criteria, searchOptions, isHierarchyEntity, allowsNonAnalytic } = options;
  if (mode === "ADVANCED") {
    return new Promise((accept, reject) => {
      const pesquisaContent = document.createElement("snk-pesquisa");
      pesquisaContent[ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME] = `entity_${entity}`;
      pesquisaContent.entityName = entity;
      pesquisaContent.argument = argument;
      pesquisaContent.searchLoader = (text) => pesquisaFetcher.loadAdvancedSearch(entity, text, criteria, searchOptions);
      pesquisaContent.isHierarchyEntity = isHierarchyEntity;
      if (isHierarchyEntity) {
        pesquisaContent.treeLoader = (text) => pesquisaFetcher.loadTree(entity, text, criteria, searchOptions);
        pesquisaContent.allowsNonAnalytic = allowsNonAnalytic;
      }
      pesquisaContent.selectItem = (option) => {
        accept(option);
        app.clearPopUpTitle();
        app.closePopUp();
      };
      app.setPopUpTitle(entityDescription);
      app.showPopUp(pesquisaContent, undefined, undefined, reject);
    });
  }
  else if (mode === "LOAD_DESCRIPTION") {
    let result = await pesquisaFetcher.loadByCode(entity, argument, criteria, searchOptions);
    result = ObjectUtils.stringToObject(result.json.$);
    let descriptionField = result.descriptionField;
    const option = (_a = result.data) === null || _a === void 0 ? void 0 : _a[0];
    if (!option) {
      return {
        value: argument,
        label: ""
      };
    }
    return {
      value: argument,
      label: option[descriptionField]
    };
  }
  else {
    let codeValue;
    let result = await pesquisaFetcher.loadAdvancedSearch(entity, argument, criteria, searchOptions, codeValue);
    result = ObjectUtils.stringToObject(result.json.$);
    let descriptionField = result.descriptionField;
    let pkField = result.pkField;
    const list = result.data.map((item) => {
      let fieldsMetadata = filterInvalidFields(result, item, mdByName);
      let fields = filterMathFields(item['__matchFields'], fieldsMetadata, QTD_DETAIL_FIELDS_PREDICTIVE_SEARCH, mdByName);
      return buildOptionItem(argument, item, fields, descriptionField, pkField);
    });
    return list;
  }
};
const buildOptionItem = (argument, item, fields, descriptionField, pkField) => {
  var _a;
  const matchFields = item['__matchFields'];
  const descriptionValue = (_a = item[descriptionField]) !== null && _a !== void 0 ? _a : "";
  const pkValue = item[pkField];
  let searchOption = {
    value: pkValue,
    label: descriptionValue,
    presentationValue: StringUtils.highlightValue(argument, matchFields, pkValue, fields, true),
    presentationLabel: descriptionField ? StringUtils.highlightValue(argument, matchFields, descriptionValue, fields, true) : "",
    details: SearchUtils.buildDetails(argument, fields, item)
  };
  return searchOption;
};
const filterInvalidFields = (resp, item, mdByName) => {
  let fieldsMetadata = resp.fieldsMetadata.filter((field) => {
    let accept = !StringUtils.isEmpty(item[field.fieldName]) &&
      field.visible !== false &&
      field.type !== 'B' &&
      resp.pkField !== field.fieldName &&
      resp.descriptionField !== field.fieldName &&
      (field.isPrimaryKey || !field.isLinkField) &&
      !(field.type === 'S' && field.presentationType === 'H');
    if (accept) {
      mdByName[field.fieldName] = field;
    }
    //Condição que trata o problema de trazer imagem no entityCard na pesquisa de registros
    if (typeof item[field.fieldName] === 'string' && INVALID_CONTENT_PATTERNS.some(pattern => item[field.fieldName].includes(pattern))) {
      return false;
    }
    return accept;
  });
  return fieldsMetadata;
};
const filterMathFields = (matchFields, fields, qtyFields, mdByName) => {
  if (matchFields && Array.isArray(matchFields)) {
    matchFields.forEach((matchField) => {
      let fieldMD = ArrayUtils.removeReference(fields, mdByName[matchField]);
      if (fieldMD) {
        fields.unshift(fieldMD);
      }
    });
  }
  fields = fields.slice(0, qtyFields);
  return fields;
};
export default executePreparedSearchPlus;
