"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchDrugAutocomplete = void 0;

var _createId = require("./create-id");

const fields = ['RXCUIS', 'STRENGTHS_AND_FORMS'];

const fetchDrugAutocomplete = term => {
  if (!term) {
    return Promise.resolve([]);
  }

  const unknownResult = {
    id: (0, _createId.createId)('unknown'),
    name: term,
    noMatch: true
  };
  return fetch("https://clinicaltables.nlm.nih.gov/api/rxterms/v3/search?ef=".concat(fields.join(','), "&terms=").concat(encodeURIComponent(term))).then(res => res.json()).then(parsed => {
    const nameList = parsed[1];
    const extraFields = parsed[2];
    const {
      RXCUIS,
      STRENGTHS_AND_FORMS
    } = extraFields || {};
    return nameList.map((name, index) => ({
      name,
      id: RXCUIS[index] && RXCUIS[index][0],
      forms: STRENGTHS_AND_FORMS[index]
    }));
  }).then(result => {
    result.push(unknownResult);
    return result;
  }).catch(() => [unknownResult]);
};

exports.fetchDrugAutocomplete = fetchDrugAutocomplete;