"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = useLDflex;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _react = require("react");

var _useWebId = _interopRequireDefault(require("./useWebId"));

var _ExpressionEvaluator = _interopRequireDefault(require("../ExpressionEvaluator"));

const value = {
  result: undefined,
  pending: true,
  error: undefined
};
const list = {
  result: [],
  pending: true,
  error: undefined
};
const none = {};
/**
 * Evaluates the Solid LDflex expression.
 * Returns an array of [result, pending, error].
 */

function useLDflex(expression, listMode = false) {
  // Expression values might differ based on the user's WebID
  const webId = (0, _useWebId.default)();

  let _useState = (0, _react.useState)(listMode ? list : value),
      _useState$ = _useState[0],
      result = _useState$.result,
      pending = _useState$.pending,
      error = _useState$.error,
      update = _useState[1]; // Set up the expression evaluator


  (0, _react.useEffect)(() => {
    const evaluator = new _ExpressionEvaluator.default();
    const query = {
      result: expression
    };
    evaluator.evaluate(!listMode ? query : none, listMode ? query : none, changed => update(current => (0, _extends2.default)({}, current, changed)));
    return () => evaluator.destroy();
  }, [expression, webId && typeof expression === 'string']); // Return the state components

  return [result, pending, error];
}