import { DataFetcher } from '../';
import { ApplicationContext, SortMode } from '@sankhyalabs/core';
export class CrudUtils {
  static assertDefaultSorting(gridConfig, dataUnit) {
    if (gridConfig && dataUnit) {
      dataUnit.defaultSorting = gridConfig
        .columns
        .filter(col => col.ascending != undefined)
        .sort((colA, colB) => colA.orderIndex - colB.orderIndex)
        .map(({ name: field, ascending }) => {
        const { dataType } = dataUnit.getField(field);
        return { field, dataType, mode: ascending ? SortMode.ASC : SortMode.DESC };
      });
    }
  }
  static parseCrudResults(entities, onlyFirst) {
    if (!Array.isArray(entities)) {
      entities = [entities];
    }
    const crudFindResults = [];
    for (const entity of entities) {
      let crudFindResult = {
        fields: new Map()
      };
      for (let key in entity) {
        let fieldValue = entity[key];
        if (fieldValue.hasOwnProperty('$')) {
          crudFindResult.fields.set(key, fieldValue.$);
        }
        if (onlyFirst) {
          break;
        }
      }
      crudFindResults.push(crudFindResult);
    }
    return crudFindResults.length > 1 ? crudFindResults : crudFindResults[0];
  }
  static find(entityName, fields, criteria, onlyFirst = true, criteriaExpression, orderBy) {
    const SERVICE_CRUD_FIND = "mge@crud.find";
    let parsedFields = [];
    let parsedCriteria = [];
    let literalCriteria = {};
    let application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    if (fields) {
      if (!Array.isArray(fields)) {
        throw new Error(application.messagesBuilder.getMessage("crudUtils.errorArray", null));
      }
      fields.forEach((fieldName) => {
        parsedFields.push({
          name: fieldName
        });
      });
    }
    if (criteria) {
      for (const key in criteria) {
        if (criteria.hasOwnProperty(key)) {
          parsedCriteria.push({ nome: key, valor: criteria[key] });
        }
      }
    }
    ;
    if (criteriaExpression) {
      literalCriteria = {
        expression: {
          $: criteriaExpression
        }
      };
    }
    let request = {
      requestBody: {
        entity: {
          name: entityName,
          criterio: parsedCriteria,
          fields: {
            field: parsedFields
          },
          literalCriteria: literalCriteria,
          orderby: orderBy
        }
      }
    };
    return new Promise((resolve) => {
      DataFetcher.get().callServiceBroker(SERVICE_CRUD_FIND, JSON.stringify(request)).then((result) => {
        var _a;
        let entities = (_a = result.entidades) === null || _a === void 0 ? void 0 : _a.entidade;
        if (!entities) {
          resolve(null);
        }
        const crudFindResults = this.parseCrudResults(entities, onlyFirst);
        resolve(crudFindResults);
      });
    });
  }
}
