"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

require("core-js/modules/es.object.set-prototype-of.js");

require("core-js/modules/es.object.get-prototype-of.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.reflect.construct.js");

require("core-js/modules/es.object.create.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.object.keys.js");

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.array.filter.js");

require("core-js/modules/es.object.get-own-property-descriptor.js");

require("core-js/modules/es.array.for-each.js");

require("core-js/modules/web.dom-collections.for-each.js");

require("core-js/modules/es.object.get-own-property-descriptors.js");

require("core-js/modules/es.object.define-properties.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

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

require("regenerator-runtime/runtime.js");

require("core-js/modules/es.function.name.js");

require("core-js/modules/es.array.map.js");

require("core-js/modules/es.regexp.exec.js");

require("core-js/modules/es.string.replace.js");

require("core-js/modules/es.string.split.js");

require("core-js/modules/es.object.define-property.js");

var _common = require("../../common");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var SearchResult = /*#__PURE__*/function (_BaseResourceWithId) {
  _inherits(SearchResult, _BaseResourceWithId);

  var _super = _createSuper(SearchResult);

  /**
   * Search result name.
   */

  /**
   * Search result type.
   */

  /**
   * Search result highlight.
   */
  function SearchResult(name, type, highlight) {
    var _this;

    _classCallCheck(this, SearchResult);

    _this = _super.call(this);

    _defineProperty(_assertThisInitialized(_this), "name", void 0);

    _defineProperty(_assertThisInitialized(_this), "type", void 0);

    _defineProperty(_assertThisInitialized(_this), "highlight", void 0);

    _this.name = name;
    _this.type = type;
    _this.highlight = highlight;
    return _this;
  }
  /**
   * Name of the resource.
   */


  _createClass(SearchResult, null, [{
    key: "resourceName",
    get: function get() {
      return "objects";
    }
    /**
     * The name of the service the resource belongs to.
     */

  }, {
    key: "serviceName",
    get: function get() {
      return "search";
    }
    /**
     * Create a search-result from the API server data.
     *
     * @param data Data from the api server.
     *
     * @returns The search-result object.
     */

  }, {
    key: "apiFactory",
    value: function apiFactory(data) {
      var result = new SearchResult(data.name, data.type, data.highlight);
      result.id = data.id;
      return result;
    }
    /**
     * Create a search-response from the API server data.
     *
     * @param data Data from the api server.
     *
     * @returns The search-response object.
     */

  }, {
    key: "searchResponseApiFactory",
    value: function searchResponseApiFactory(data) {
      var _this2 = this;

      return {
        total: data.total,
        counts: data.counts.map(function (_ref) {
          var key = _ref.key,
              doc_count = _ref.doc_count;
          return {
            key: key,
            docCount: doc_count
          };
        }),
        hits: data.hits.map(function (hit) {
          return _this2.apiFactory(hit);
        })
      };
    }
    /**
     * Searches for suggestions by the query.
     *
     * @param query Query string.
     * @param pageSize Optional amount of elements to be returned.
     */

  }, {
    key: "suggest",
    value: function () {
      var _suggest = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(query, pageSize, cancelToken) {
        var _this3 = this;

        var server, queryParams, response;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                server = new _common.APIServer();
                queryParams = _objectSpread({
                  q: query.replace(" ", "%")
                }, pageSize ? {
                  page_size: "".concat(pageSize)
                } : {});
                _context.next = 4;
                return server.get("".concat(this.path, "suggest"), undefined, queryParams, {
                  cancelToken: cancelToken
                });

              case 4:
                response = _context.sent;

                if (!response.error) {
                  _context.next = 7;
                  break;
                }

                throw new _common.APIResponseError("Error while searching for ".concat(query), response);

              case 7:
                return _context.abrupt("return", response.data.map(function (result) {
                  return _this3.apiFactory(result);
                }));

              case 8:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function suggest(_x, _x2, _x3) {
        return _suggest.apply(this, arguments);
      }

      return suggest;
    }()
    /**
     * Returns list of items that match the query arguments
     *
     * @param args Query arguments object.
     */

  }, {
    key: "query",
    value: function () {
      var _query = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(args, cancelToken) {
        var server, queryParams, response;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                server = new _common.APIServer();
                queryParams = {
                  q: args.query.split(" "),
                  type: args.type,
                  page: args.page,
                  page_size: args.pageSize,
                  facet: args.facet
                }; // Remove empty keys

                (0, _common.cleanUpQueryParams)(queryParams);
                _context2.next = 5;
                return server.get("".concat(this.path, "query"), undefined, queryParams, {
                  cancelToken: cancelToken
                });

              case 5:
                response = _context2.sent;

                if (!response.error) {
                  _context2.next = 8;
                  break;
                }

                throw new _common.APIResponseError("Error while searching for ".concat(args.query), response);

              case 8:
                return _context2.abrupt("return", this.searchResponseApiFactory(response.data));

              case 9:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function query(_x4, _x5) {
        return _query.apply(this, arguments);
      }

      return query;
    }()
  }]);

  return SearchResult;
}(_common.BaseResourceWithId);

exports.SearchResult = SearchResult;
//# sourceMappingURL=data:application/json;charset=utf-8;base64, 