{"size": 1505, "ext": "js", "max_stars_repo_path": "lib/utils/parse_rets_query.js", "max_stars_repo_name": "mslosarek/node-rets", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/utils/parse_rets_query.js", "max_issues_repo_name": "mslosarek/node-rets", "max_issues_repo_issues_event_min_datetime": "2020-05-10T03:07:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T09:33:46.000Z", "max_forks_repo_path": "lib/utils/parse_rets_query.js", "max_forks_repo_name": "mslosarek/node-rets", "max_forks_repo_forks_event_min_datetime": "2021-03-12T21:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T21:49:34.000Z"}
{"max_stars_count": null, "max_issues_count": 3, "max_forks_count": 1, "avg_line_length": 25.5084745763, "max_line_length": 88, "alphanum_fraction": 0.6671096346}
const { isArray, chain } = require('underscore');

const ParseRetsResponseXML = require('./parse_rets_response_xml.js');
const { FlattenObject } = require('./common.js');

async function ParseRetsQuery(xmlContent, defaultFlatten = true) {
  let knownResponse = false;
  let flatten = defaultFlatten;

  const queryJSON = await ParseRetsResponseXML(xmlContent);

  const queryResponse = {};
  if (queryJSON.COUNT && queryJSON.COUNT.$.Records) {
    queryResponse.TotalCount = Number(queryJSON.COUNT.$.Records);
  }

  if (queryJSON.DATA) {
    knownResponse = true;
    queryResponse.Objects = queryJSON.DATA;
  } else if (queryJSON['RETS-RESPONSE'] && queryJSON['RETS-RESPONSE'].PropertyDetails) {
    // handle CREA Standard XML
    knownResponse = true;
    flatten = false;

    let data = queryJSON['RETS-RESPONSE'].PropertyDetails;

    if (!isArray(data)) {
      data = [data];
    }

    queryResponse.Objects = data;
  } else if (queryJSON.REData) {
    knownResponse = true;
    let data = chain(queryJSON.REData)
    .values()
    .first()
    .values()
    .first()
    .value();

    if (!isArray(data)) {
      data = [data];
    }
    queryResponse.Objects = data;
  } else {
    queryResponse.Response = queryJSON;
  }

  if (knownResponse) {
    if (flatten && knownResponse) {
      queryResponse.Objects = queryResponse.Objects.map(obj => FlattenObject(obj));
    }
    queryResponse.Count = queryResponse.Objects.length;
  }

  return queryResponse;
}
module.exports = ParseRetsQuery;
