import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import React, { Component } from "react";
import { Utils } from "@react-awesome-query-builder/core";
import PropTypes from "prop-types";
import { truncateString } from "../../utils/stuff";
import { useOnPropsChanged } from "../../utils/reactUtils";
import last from "lodash/last";
import keys from "lodash/keys";
var clone = Utils.clone;
var _Utils$ConfigUtils = Utils.ConfigUtils,
  getFieldConfig = _Utils$ConfigUtils.getFieldConfig,
  getFuncConfig = _Utils$ConfigUtils.getFuncConfig,
  getFieldParts = _Utils$ConfigUtils.getFieldParts,
  getFieldPathParts = _Utils$ConfigUtils.getFieldPathParts,
  getWidgetForFieldOp = _Utils$ConfigUtils.getWidgetForFieldOp;
var getFuncPathLabels = Utils.RuleUtils.getFuncPathLabels;
var shallowEqual = Utils.OtherUtils.shallowEqual;

//tip: this.props.value - right value, this.props.field - left value
var FuncSelect = /*#__PURE__*/function (_Component) {
  function FuncSelect(props) {
    var _this;
    _classCallCheck(this, FuncSelect);
    _this = _callSuper(this, FuncSelect, [props]);
    useOnPropsChanged(_this);
    _this.onPropsChanged(props);
    return _this;
  }
  _inherits(FuncSelect, _Component);
  return _createClass(FuncSelect, [{
    key: "onPropsChanged",
    value: function onPropsChanged(nextProps) {
      var prevProps = this.props;
      var keysForItems = ["config", "field", "fieldType", "fieldSrc", "operator", "isFuncArg", "isLHS", "parentFuncs"];
      var keysForMeta = ["config", "field", "fieldType", "fieldSrc", "value", "isLHS"];
      var needUpdateItems = !this.items || keysForItems.map(function (k) {
        return k === "parentFuncs" ? !shallowEqual(nextProps[k], prevProps[k], true) : nextProps[k] !== prevProps[k];
      }).filter(function (ch) {
        return ch;
      }).length > 0;
      var needUpdateMeta = !this.meta || keysForMeta.map(function (k) {
        return nextProps[k] !== prevProps[k];
      }).filter(function (ch) {
        return ch;
      }).length > 0;
      if (needUpdateMeta) {
        this.meta = this.getMeta(nextProps);
      }
      if (needUpdateItems) {
        this.items = this.getItems(nextProps, this.meta);
      }
    }
  }, {
    key: "getItems",
    value: function getItems(_ref, _ref2) {
      var config = _ref.config,
        field = _ref.field,
        fieldType = _ref.fieldType,
        isLHS = _ref.isLHS,
        operator = _ref.operator,
        parentFuncs = _ref.parentFuncs,
        fieldDefinition = _ref.fieldDefinition,
        isFuncArg = _ref.isFuncArg;
      var lookingForFieldType = _ref2.lookingForFieldType;
      var canUseFuncForField = config.settings.canUseFuncForField;
      var filteredFuncs = this.filterFuncs(config, config.funcs, field, fieldType, isLHS, operator, canUseFuncForField, parentFuncs, isFuncArg, fieldDefinition);
      var items = this.buildOptions(config, filteredFuncs, lookingForFieldType);
      return items;
    }
  }, {
    key: "getMeta",
    value: function getMeta(_ref3) {
      var config = _ref3.config,
        _field = _ref3._field,
        fieldType = _ref3.fieldType,
        value = _ref3.value,
        isLHS = _ref3.isLHS,
        isFuncArg = _ref3.isFuncArg;
      var _config$settings = config.settings,
        funcPlaceholder = _config$settings.funcPlaceholder,
        fieldSeparatorDisplay = _config$settings.fieldSeparatorDisplay;
      var selectedFuncKey = value;
      var isFuncSelected = !!value;

      // const leftFieldConfig = getFieldConfig(config, field);
      // const leftFieldWidgetField = leftFieldConfig?.widgets?.field;
      // const leftFieldWidgetFieldProps = leftFieldWidgetField && leftFieldWidgetField.widgetProps || {};
      var placeholder = !isFuncSelected ? funcPlaceholder : null;
      var currFunc = isFuncSelected ? getFuncConfig(config, selectedFuncKey) : null;
      var selectedOpts = currFunc || {};
      var selectedKeys = getFieldPathParts(selectedFuncKey, config);
      var selectedPath = getFieldPathParts(selectedFuncKey, config, true);
      var selectedLabel = this.getFuncLabel(currFunc, selectedFuncKey, config);
      var partsLabels = getFuncPathLabels(selectedFuncKey, config);
      var selectedFullLabel = partsLabels ? partsLabels.join(fieldSeparatorDisplay) : null;
      if (selectedFullLabel == selectedLabel) selectedFullLabel = null;
      var isRootFuncAtLHS = isLHS && !isFuncArg;
      var lookingForFieldType = isRootFuncAtLHS && !isFuncSelected && fieldType;
      // Field source has been chnaged, no new func selected, but op & value remains
      var errorText = lookingForFieldType ? "Please select function" : null;
      return {
        placeholder: placeholder,
        selectedKey: selectedFuncKey,
        selectedKeys: selectedKeys,
        selectedPath: selectedPath,
        selectedLabel: selectedLabel,
        selectedOpts: selectedOpts,
        selectedFullLabel: selectedFullLabel,
        errorText: errorText,
        lookingForFieldType: lookingForFieldType
      };
    }
  }, {
    key: "filterFuncs",
    value: function filterFuncs(config, funcs, leftFieldFullkey, fieldType, isLHS, operator, canUseFuncForField, parentFuncs, isFuncArg, fieldDefinition) {
      funcs = clone(funcs);
      var fieldSeparator = config.settings.fieldSeparator;
      var leftFieldConfig = getFieldConfig(config, leftFieldFullkey);
      var _relyOnWidgetType = false; //TODO: remove this, see issue #758
      var expectedType;
      var targetDefinition = leftFieldConfig;
      var widget = getWidgetForFieldOp(config, leftFieldFullkey, operator, "value");
      var widgetConfig = widget && config.widgets[widget];
      if (isFuncArg) {
        targetDefinition = fieldDefinition;
        expectedType = fieldDefinition === null || fieldDefinition === void 0 ? void 0 : fieldDefinition.type;
      } else if (_relyOnWidgetType && widgetConfig) {
        expectedType = widgetConfig.type;
      } else if (leftFieldConfig) {
        expectedType = leftFieldConfig.type;
      } else if (!isLHS) {
        // no field at LHS, but can use type from "memory effect"
        expectedType = fieldType;
      }
      function _filter(list, path) {
        for (var funcKey in list) {
          var subfields = list[funcKey].subfields;
          var subpath = (path ? path : []).concat(funcKey);
          var funcFullkey = subpath.join(fieldSeparator);
          var funcConfig = getFuncConfig(config, funcFullkey);
          if (funcConfig.type == "!struct") {
            if (_filter(subfields, subpath) == 0) delete list[funcKey];
          } else {
            var _targetDefinition;
            var canUse = !expectedType || funcConfig.returnType == expectedType;
            if ((_targetDefinition = targetDefinition) !== null && _targetDefinition !== void 0 && _targetDefinition.funcs) canUse = canUse && targetDefinition.funcs.includes(funcFullkey);
            if (canUseFuncForField) canUse = canUse && canUseFuncForField(leftFieldFullkey, leftFieldConfig, funcFullkey, funcConfig, operator);
            // don't use func in func (can be configurable, but usually users don't need this)
            if (!funcConfig.allowSelfNesting && parentFuncs && parentFuncs.map(function (_ref4) {
              var _ref5 = _slicedToArray(_ref4, 2),
                func = _ref5[0],
                _arg = _ref5[1];
              return func;
            }).includes(funcFullkey)) canUse = false;
            if (!canUse) delete list[funcKey];
          }
        }
        return keys(list).length;
      }
      _filter(funcs, []);
      return funcs;
    }
  }, {
    key: "buildOptions",
    value: function buildOptions(config, funcs) {
      var _this2 = this;
      var fieldType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
      var path = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
      var optGroup = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
      if (!funcs) return null;
      var _config$settings2 = config.settings,
        fieldSeparator = _config$settings2.fieldSeparator,
        fieldSeparatorDisplay = _config$settings2.fieldSeparatorDisplay;
      var prefix = path !== null && path !== void 0 && path.length ? path.join(fieldSeparator) + fieldSeparator : "";
      var countFieldsMatchesType = function countFieldsMatchesType(fields) {
        return Object.keys(fields || {}).reduce(function (acc, fieldKey) {
          var field = fields[fieldKey];
          if (field.type === "!struct") {
            return acc + countFieldsMatchesType(field.subfields);
          } else {
            return acc + (field.type === fieldType ? 1 : 0);
          }
        }, 0);
      };
      return keys(funcs).map(function (funcKey) {
        var fullFuncPath = [].concat(_toConsumableArray(path !== null && path !== void 0 ? path : []), [funcKey]);
        var func = funcs[funcKey];
        var label = _this2.getFuncLabel(func, fullFuncPath, config);
        var partsLabels = getFuncPathLabels(fullFuncPath, config);
        var fullLabel = partsLabels.join(fieldSeparatorDisplay);
        if (fullLabel == label) fullLabel = null;
        var tooltip = func.tooltip;
        if (func.type == "!struct") {
          var items = _this2.buildOptions(config, func.subfields, fieldType, fullFuncPath, {
            label: label,
            tooltip: tooltip
          });
          var hasItemsMatchesType = countFieldsMatchesType(func.subfields) > 0;
          return {
            key: funcKey,
            path: prefix + funcKey,
            label: label,
            fullLabel: fullLabel,
            tooltip: tooltip,
            items: items,
            matchesType: hasItemsMatchesType
          };
        } else {
          var matchesType = fieldType !== undefined ? func.returnType === fieldType : undefined;
          return {
            key: funcKey,
            path: prefix + funcKey,
            label: label,
            fullLabel: fullLabel,
            tooltip: tooltip,
            grouplabel: optGroup === null || optGroup === void 0 ? void 0 : optGroup.label,
            group: optGroup,
            matchesType: matchesType
          };
        }
      });
    }
  }, {
    key: "getFuncLabel",
    value: function getFuncLabel(funcOpts, funcKey, config) {
      if (!funcKey) return null;
      var maxLabelsLength = config.settings.maxLabelsLength;
      var funcParts = getFieldParts(funcKey, config);
      var label = (funcOpts === null || funcOpts === void 0 ? void 0 : funcOpts.label) || last(funcParts);
      label = truncateString(label, maxLabelsLength);
      return label;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
        config = _this$props.config,
        customProps = _this$props.customProps,
        setValue = _this$props.setValue,
        readonly = _this$props.readonly,
        id = _this$props.id,
        groupId = _this$props.groupId;
      var renderFunc = config.settings.renderFunc;
      var renderProps = _objectSpread({
        config: config,
        customProps: customProps,
        readonly: readonly,
        setField: setValue,
        items: this.items,
        id: id,
        groupId: groupId
      }, this.meta);
      return renderFunc(renderProps, config.ctx);
    }
  }]);
}(Component);
FuncSelect.propTypes = {
  id: PropTypes.string,
  groupId: PropTypes.string,
  config: PropTypes.object.isRequired,
  field: PropTypes.any,
  fieldType: PropTypes.string,
  fieldSrc: PropTypes.string,
  operator: PropTypes.string,
  customProps: PropTypes.object,
  value: PropTypes.string,
  setValue: PropTypes.func.isRequired,
  readonly: PropTypes.bool,
  parentFuncs: PropTypes.array,
  fieldDefinition: PropTypes.object,
  isFuncArg: PropTypes.bool,
  isLHS: PropTypes.bool
};
export { FuncSelect as default };