'use strict';

var _extends = require('@babel/runtime/helpers/extends');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.function.name.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var react = require('@carbon/react');
var PropTypes = require('prop-types');
var Settings = require('../../constants/Settings.js');
var Button = require('../Button/Button.js');
var GroupLogic = require('./GroupLogic.js');
var RuleBuilderPropTypes = require('./RuleBuilderPropTypes.js');
var RuleValueField = require('./RuleValueField.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__namespace = /*#__PURE__*/_interopNamespace(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);

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__default.default(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; }
var iotPrefix = Settings.settings.iotPrefix;
var defaultProps = {
  i18n: {
    all: 'ALL',
    any: 'ANY',
    contains: 'Contains',
    lessThan: 'Less than',
    lessThanOrEqual: 'Less than or equal to',
    notEqual: 'Not equal',
    equals: 'Equals',
    greaterThanOrEqual: 'Greater than or equal to',
    greaterThan: 'Greater than',
    selectAColumn: 'Select a column',
    selectAnOperand: 'Select an operand'
  }
};
var propTypes = {
  rule: PropTypes__default.default.oneOfType([RuleBuilderPropTypes.RulesPropType, RuleBuilderPropTypes.RuleGroupPropType]).isRequired,
  // see RuleBuilderEditor proptypes for details.
  columns: RuleBuilderPropTypes.RuleBuilderColumnsPropType.isRequired,
  /**
   * Function passed from RuleBuilderEditor that takes two optional parameters. The id is
   * used to find this rule in the tree and insert the new rule (or group) after it.
   *
   * @param {string} id the Id of the rule where the add button was clicked.
   * @param {boolean} isGroup A boolean indicating if the new rule to be added is a rule group
   */
  onAddRule: PropTypes__default.default.func.isRequired,
  /**
   * Factory function passed from RuleBuilderEditor that takes one parameter. The id is
   * used to find this rule in the tree and remove it.
   *
   * @param {string} id the Id of the rule where the remove button was clicked.
   */
  onRemoveRule: PropTypes__default.default.func.isRequired,
  /**
   * The onChange callback called on any updates to this rule.
   * For example, if the value field of a rule were changed the callback would contain two parameters the changed object:
   * { id: 'ruleid-1', value: 'new-value' } and a boolean of false indicating it was a nested rule that was changed.
   *
   * However, if the root groupLogic were changed from ALL to ANY. The callback would contain:
   * { id: 'groupid-x', groupLogic: 'ANY' }, and a boolean of true indicating the root tree was changed.
   *
   * Finally, if any other properties of the rule were changes (column or operand) the onChange callback would contain:
   * { id: 'ruleid-y', columnId: 'new-column-id' } or { id: 'ruleid-', operand: 'new-operand-id' }
   *
   * @param {object} changed On object containing the rule id, and the parameters that have been updated.
   * @param {boolean} isRoot Did this change happen to the root object of the tree or nested down.
   */
  onChange: PropTypes__default.default.func.isRequired,
  i18n: PropTypes__default.default.shape({
    all: PropTypes__default.default.string,
    any: PropTypes__default.default.string,
    contains: PropTypes__default.default.string,
    lessThan: PropTypes__default.default.string,
    lessThanOrEqual: PropTypes__default.default.string,
    notEqual: PropTypes__default.default.string,
    equals: PropTypes__default.default.string,
    greaterThanOrEqual: PropTypes__default.default.string,
    greaterThan: PropTypes__default.default.string,
    selectAColumn: PropTypes__default.default.string,
    selectAnOperand: PropTypes__default.default.string
  })
};
function Rule(_ref) {
  var rule = _ref.rule,
    onAddRule = _ref.onAddRule,
    onRemoveRule = _ref.onRemoveRule,
    onChange = _ref.onChange,
    columns = _ref.columns,
    i18n = _ref.i18n;
  var ruleId = rule.id,
    operand = rule.operand,
    columnId = rule.columnId,
    groupLogic = rule.groupLogic,
    rules = rule.rules;
  var mergedI18n = React__namespace.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n !== null && i18n !== void 0 ? i18n : {});
  }, [i18n]);
  var defaultOperands = React__namespace.useMemo(function () {
    return [{
      id: 'NEQ',
      name: mergedI18n.notEqual
    }, {
      id: 'LT',
      name: mergedI18n.lessThan
    }, {
      id: 'LTOET',
      name: mergedI18n.lessThanOrEqual
    }, {
      id: 'EQ',
      name: mergedI18n.equals
    }, {
      id: 'GTOET',
      name: mergedI18n.greaterThanOrEqual
    }, {
      id: 'GT',
      name: mergedI18n.greaterThan
    }, {
      id: 'CONTAINS',
      name: mergedI18n.contains
    }];
  }, [mergedI18n]);
  var getColumnById = React__namespace.useMemo(function () {
    return function (id) {
      return columns === null || columns === void 0 ? void 0 : columns.find(function (_ref2) {
        var colId = _ref2.id;
        return id === colId;
      });
    };
  }, [columns]);
  var selectedColumn = React__namespace.useMemo(function () {
    return getColumnById(columnId);
  }, [columnId, getColumnById]);
  var columnOperands = React__namespace.useMemo(function () {
    if (selectedColumn && selectedColumn.operands) {
      return selectedColumn.operands;
    }
    return defaultOperands;
  }, [defaultOperands, selectedColumn]);
  var getOperandById = React__namespace.useMemo(function () {
    return function (opId) {
      return columnOperands.find(function (_ref3) {
        var id = _ref3.id;
        return id === opId;
      });
    };
  }, [columnOperands]);
  var getOperandByColumnId = React__namespace.useMemo(function () {
    return function (id) {
      var col = getColumnById(id);
      var operands = col && col.operands || defaultOperands;
      var foundOp = operands.find(function (op) {
        return op.id === operand;
      });
      if (foundOp) {
        return foundOp.id;
      }
      return operands[0].id;
    };
  }, [defaultOperands, getColumnById, operand]);
  var handleChangeOperand = React__namespace.useCallback(function (_ref4) {
    var selectedItem = _ref4.selectedItem;
    onChange({
      id: ruleId,
      operand: selectedItem.id
    });
  }, [ruleId, onChange]);
  var handleChangeColumn = React__namespace.useCallback(function (_ref5) {
    var selectedItem = _ref5.selectedItem;
    onChange({
      id: ruleId,
      columnId: selectedItem.id,
      operand: getOperandByColumnId(selectedItem.id)
    });
  }, [getOperandByColumnId, onChange, ruleId]);
  var handleChangeValue = React__namespace.useCallback(function (newValue) {
    onChange({
      id: ruleId,
      value: newValue
    });
  }, [ruleId, onChange]);
  var handleChangeGroupLogic = React__namespace.useCallback(function (_ref6) {
    var selectedItem = _ref6.selectedItem;
    onChange({
      id: ruleId,
      groupLogic: selectedItem.id
    });
  }, [ruleId, onChange]);
  var selectedOperand = React__namespace.useMemo(function () {
    return getOperandById(operand);
  }, [getOperandById, operand]);
  if (groupLogic && Array.isArray(rules)) {
    return /*#__PURE__*/React__namespace.createElement("div", {
      className: "".concat(iotPrefix, "--rule-builder-rule--group")
    }, /*#__PURE__*/React__namespace.createElement(GroupLogic, {
      id: ruleId,
      selected: groupLogic,
      onChange: handleChangeGroupLogic,
      i18n: mergedI18n
    }), rules.map(function (subRule) {
      return /*#__PURE__*/React__namespace.createElement(Rule, {
        rule: _objectSpread({}, subRule),
        key: subRule.id,
        onAddRule: onAddRule,
        onRemoveRule: onRemoveRule,
        onChange: onChange,
        columns: columns
      });
    }));
  }
  return /*#__PURE__*/React__namespace.createElement("div", {
    "data-testid": "".concat(ruleId, "-rule"),
    className: "".concat(iotPrefix, "--rule-builder-rule")
  }, /*#__PURE__*/React__namespace.createElement(react.Dropdown, {
    id: "".concat(ruleId, "-column-dropdown"),
    light: true,
    items: columns,
    label: selectedColumn && selectedColumn.name || mergedI18n.selectAColumn,
    itemToString: function itemToString(item) {
      return item.name;
    },
    selectedItem: selectedColumn,
    initialSelectedItem: selectedColumn,
    onChange: handleChangeColumn,
    "data-testid": "".concat(ruleId, "-column-dropdown")
  }), /*#__PURE__*/React__namespace.createElement(react.Dropdown, {
    id: "".concat(ruleId, "-operand-dropdown"),
    light: true,
    items: columnOperands,
    itemToString: function itemToString(item) {
      return item.name;
    },
    label: selectedOperand && selectedOperand.name || mergedI18n.selectAnOperand,
    selectedItem: selectedOperand,
    initialSelectedItem: selectedOperand,
    onChange: handleChangeOperand,
    "data-testid": "".concat(ruleId, "-operand-dropdown")
  }), /*#__PURE__*/React__namespace.createElement(RuleValueField, {
    rule: rule,
    onChange: handleChangeValue,
    renderColumnField: selectedColumn === null || selectedColumn === void 0 ? void 0 : selectedColumn.renderField,
    renderOperandField: selectedOperand === null || selectedOperand === void 0 ? void 0 : selectedOperand.renderField
  }), /*#__PURE__*/React__namespace.createElement("div", {
    className: "".concat(iotPrefix, "--rule-builder-rule__actions")
  }, /*#__PURE__*/React__namespace.createElement(Button, {
    hasIconOnly: true,
    renderIcon: function renderIcon(props) {
      return /*#__PURE__*/React__namespace.createElement(iconsReact.Subtract, _extends__default.default({
        size: 16
      }, props));
    },
    kind: "ghost",
    tooltipPosition: "top",
    iconDescription: "Remove rule",
    onClick: onRemoveRule(ruleId),
    testId: "".concat(ruleId, "-remove-rule-button")
  }), /*#__PURE__*/React__namespace.createElement(Button, {
    hasIconOnly: true,
    renderIcon: function renderIcon(props) {
      return /*#__PURE__*/React__namespace.createElement(iconsReact.Add, _extends__default.default({
        size: 16
      }, props));
    },
    kind: "ghost",
    tooltipPosition: "top",
    iconDescription: "Add new rule",
    onClick: onAddRule(ruleId),
    testId: "".concat(ruleId, "-add-rule-button")
  }), /*#__PURE__*/React__namespace.createElement(Button, {
    hasIconOnly: true,
    renderIcon: function renderIcon(props) {
      return /*#__PURE__*/React__namespace.createElement(iconsReact.TextNewLine, _extends__default.default({
        size: 16
      }, props));
    },
    kind: "ghost",
    tooltipPosition: "top",
    iconDescription: "Add new rule group",
    onClick: onAddRule(ruleId, true),
    testId: "".concat(ruleId, "-add-group-button")
  })));
}
Rule.defaultProps = defaultProps;
Rule.propTypes = propTypes;
Rule.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "Rule",
  "props": {
    "i18n": {
      "defaultValue": {
        "value": "{\n  all: 'ALL',\n  any: 'ANY',\n  contains: 'Contains',\n  lessThan: 'Less than',\n  lessThanOrEqual: 'Less than or equal to',\n  notEqual: 'Not equal',\n  equals: 'Equals',\n  greaterThanOrEqual: 'Greater than or equal to',\n  greaterThan: 'Greater than',\n  selectAColumn: 'Select a column',\n  selectAnOperand: 'Select an operand',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "all": {
            "name": "string",
            "required": false
          },
          "any": {
            "name": "string",
            "required": false
          },
          "contains": {
            "name": "string",
            "required": false
          },
          "lessThan": {
            "name": "string",
            "required": false
          },
          "lessThanOrEqual": {
            "name": "string",
            "required": false
          },
          "notEqual": {
            "name": "string",
            "required": false
          },
          "equals": {
            "name": "string",
            "required": false
          },
          "greaterThanOrEqual": {
            "name": "string",
            "required": false
          },
          "greaterThan": {
            "name": "string",
            "required": false
          },
          "selectAColumn": {
            "name": "string",
            "required": false
          },
          "selectAnOperand": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "rule": {
      "description": "",
      "type": {
        "name": "union",
        "value": [{
          "name": "custom",
          "raw": "RulesPropType"
        }, {
          "name": "custom",
          "raw": "RuleGroupPropType"
        }]
      },
      "required": true
    },
    "columns": {
      "description": "",
      "type": {
        "name": "custom",
        "raw": "RuleBuilderColumnsPropType.isRequired"
      },
      "required": false
    },
    "onAddRule": {
      "description": "Function passed from RuleBuilderEditor that takes two optional parameters. The id is\nused to find this rule in the tree and insert the new rule (or group) after it.\n\n@param {string} id the Id of the rule where the add button was clicked.\n@param {boolean} isGroup A boolean indicating if the new rule to be added is a rule group",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "onRemoveRule": {
      "description": "Factory function passed from RuleBuilderEditor that takes one parameter. The id is\nused to find this rule in the tree and remove it.\n\n@param {string} id the Id of the rule where the remove button was clicked.",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "onChange": {
      "description": "The onChange callback called on any updates to this rule.\nFor example, if the value field of a rule were changed the callback would contain two parameters the changed object:\n{ id: 'ruleid-1', value: 'new-value' } and a boolean of false indicating it was a nested rule that was changed.\n\nHowever, if the root groupLogic were changed from ALL to ANY. The callback would contain:\n{ id: 'groupid-x', groupLogic: 'ANY' }, and a boolean of true indicating the root tree was changed.\n\nFinally, if any other properties of the rule were changes (column or operand) the onChange callback would contain:\n{ id: 'ruleid-y', columnId: 'new-column-id' } or { id: 'ruleid-', operand: 'new-operand-id' }\n\n@param {object} changed On object containing the rule id, and the parameters that have been updated.\n@param {boolean} isRoot Did this change happen to the root object of the tree or nested down.",
      "type": {
        "name": "func"
      },
      "required": true
    }
  }
};

module.exports = Rule;
