'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isEmpty = require('../../../node_modules/lodash-es/isEmpty.js');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.join.js');
require('core-js/modules/es.array.map.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 PropTypes = require('prop-types');
var react = require('@carbon/react');
var uuid = require('uuid');
var iconsReact = require('@carbon/icons-react');
var DataSeriesFormItemModal = require('../../CardEditor/CardEditForm/CardEditFormItems/DataSeriesFormItemModal.js');
var List = require('../../List/List.js');
var Button = require('../../Button/Button.js');
var Settings = require('../../../constants/Settings.js');
var deprecate = require('../../../internal/deprecate.js');
var editorUtils = require('../../DashboardEditor/editorUtils.js');
var HierarchyDataFormItems = require('../../CardEditor/CardEditForm/CardEditFormItems/HierarchyDataFormItems/HierarchyDataFormItems.js');

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

var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefault(_regeneratorRuntime);
var React__default = /*#__PURE__*/_interopDefault(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 propTypes = {
  /** The hotspot for which the data source settings should be changed. */
  hotspot: PropTypes__default.default.shape({
    content: PropTypes__default.default.shape({
      attributes: PropTypes__default.default.arrayOf(PropTypes__default.default.object)
    })
  }).isRequired,
  /** This prop is mainly needed since the HotspotEditorDataSourceTab internally makes
   * use of DataSeriesFormItemModal which has its API designed around the card config */
  cardConfig: PropTypes__default.default.shape({
    id: PropTypes__default.default.string,
    title: PropTypes__default.default.string,
    size: PropTypes__default.default.string,
    type: PropTypes__default.default.string,
    content: PropTypes__default.default.shape({
      alt: PropTypes__default.default.string,
      src: PropTypes__default.default.string,
      image: PropTypes__default.default.string,
      hideMinimap: PropTypes__default.default.bool,
      hideHotspots: PropTypes__default.default.bool,
      hideZoomControls: PropTypes__default.default.bool,
      id: PropTypes__default.default.string
    }),
    description: PropTypes__default.default.string,
    values: PropTypes__default.default.shape({
      hotspots: PropTypes__default.default.arrayOf(PropTypes__default.default.object)
    })
  }).isRequired,
  i18n: PropTypes__default.default.shape({
    selectDataItemsText: PropTypes__default.default.string,
    dataItemText: PropTypes__default.default.string,
    edit: PropTypes__default.default.string,
    remove: PropTypes__default.default.string,
    dataItemEditorDataItemTitle: PropTypes__default.default.string,
    dataItemEditorDataItemCustomLabel: PropTypes__default.default.string,
    dataItemEditorDataItemUnit: PropTypes__default.default.string,
    dataItemEditorDataItemFilter: PropTypes__default.default.string,
    dataItemEditorDataItemThresholds: PropTypes__default.default.string,
    dataItemEditorDataItemAddThreshold: PropTypes__default.default.string,
    primaryButtonLabelText: PropTypes__default.default.string,
    secondaryButtonLabelText: PropTypes__default.default.string
  }),
  /** Callback i18n function for translating ListBoxMenuIcon SVG title in the MultiSelect component */
  translateWithId: PropTypes__default.default.func.isRequired,
  /** callback when image input value changes */
  onChange: PropTypes__default.default.func.isRequired,
  // eslint-disable-next-line react/require-default-props
  testID: deprecate(PropTypes__default.default.string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
  /** Id that can be used for testing */
  testId: PropTypes__default.default.string,
  /** An array of data source items that can be selected for the specified hotspot */
  dataItems: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
    dataSourceId: PropTypes__default.default.string,
    label: PropTypes__default.default.string
  })),
  /** An object where the keys are available dimensions and the values are the values available for those dimensions
   *  ex: { manufacturer: ['Rentech', 'GHI Industries'], deviceid: ['73000', '73001', '73002'] } */
  availableDimensions: PropTypes__default.default.shape({}),
  actions: editorUtils.DashboardEditorActionsPropTypes
};
var defaultProps = {
  i18n: {
    selectDataItemsText: 'Select data items',
    dataItemText: 'Data items',
    edit: 'Edit',
    remove: 'Remove',
    dataItemEditorDataItemTitle: 'Data items',
    dataItemEditorDataItemCustomLabel: 'Custom label',
    dataItemEditorDataItemUnit: 'Unit',
    dataItemEditorDataItemFilter: 'Data filter',
    dataItemEditorDataItemThresholds: 'Thresholds',
    dataItemEditorDataItemAddThreshold: 'Add threshold',
    primaryButtonLabelText: 'Update',
    secondaryButtonLabelText: 'Cancel'
  },
  dataItems: [],
  availableDimensions: {},
  testId: 'HotspotEditorDataSourceTab',
  actions: editorUtils.defaultDashboardEditorActionsProps
};
var formatDataItemsForDropdown = function formatDataItemsForDropdown(dataItems) {
  var _dataItems$filter;
  return dataItems === null || dataItems === void 0 || (_dataItems$filter = dataItems.filter(function (dataItem) {
    return !HierarchyDataFormItems.isHierarchyDataItem(dataItem);
  }) // filter hierarchy data items
  ) === null || _dataItems$filter === void 0 ? void 0 : _dataItems$filter.map(function (_ref) {
    var dataSourceId = _ref.dataSourceId,
      label = _ref.label;
    return {
      id: dataSourceId,
      label: label
    };
  });
};
var HotspotEditorDataSourceTab = function HotspotEditorDataSourceTab(_ref2) {
  var _hotspot$content;
  var hotspot = _ref2.hotspot,
    cardConfig = _ref2.cardConfig,
    dataItems = _ref2.dataItems,
    i18n = _ref2.i18n,
    onChange = _ref2.onChange,
    availableDimensions = _ref2.availableDimensions,
    testID = _ref2.testID,
    testId = _ref2.testId,
    translateWithId = _ref2.translateWithId,
    actions = _ref2.actions;
  var mergedI18n = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    showEditor = _useState2[0],
    setShowEditor = _useState2[1];
  var _useState3 = React.useState({}),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    editDataItem = _useState4[0],
    setEditDataItem = _useState4[1];
  var selectedItemsArray = ((_hotspot$content = hotspot.content) === null || _hotspot$content === void 0 ? void 0 : _hotspot$content.attributes) || [];
  var baseClassName = "".concat(iotPrefix, "--card-edit-form");
  var onEditDataItem = actions.onEditDataItem;
  var handleSelectionChange = function handleSelectionChange(_ref3) {
    var selectedItems = _ref3.selectedItems;
    var newArray = [];
    // loop through  selected Items and find their selectedItemsArray object or the dataItem object with same id
    selectedItems.forEach(function (item) {
      var containedItem = selectedItemsArray.find(function (selectedItem) {
        return selectedItem.dataSourceId === item.id;
      });
      var containedDataItem = dataItems.find(function (selectedItem) {
        return selectedItem.dataItemId === item.id;
      });
      if (containedItem) {
        newArray.push(containedItem);
      } else if (containedDataItem) {
        newArray.push(containedDataItem);
      }
    });

    // Add existing hierarchy data items
    newArray.push.apply(newArray, _toConsumableArray__default.default(selectedItemsArray.filter(function (item) {
      return HierarchyDataFormItems.isHierarchyDataItem(item);
    })));
    onChange({
      attributes: newArray
    });
  };
  var handleHierarchyDataItemChange = React.useCallback(function (items) {
    var updatedItems = items === null || items === void 0 ? void 0 : items.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        // create a unique dataSourceId
        dataSourceId: "".concat(item.dataItemId, "_").concat(uuid.v4())
      });
    });
    var selectedItems = [].concat(_toConsumableArray__default.default(selectedItemsArray), _toConsumableArray__default.default(updatedItems));
    onChange({
      attributes: selectedItems
    });
  }, [onChange, selectedItemsArray]);

  // MultiSelect
  // For the initial selection to work the objects in prop "selectedItemsArray"
  // must be identical to the objects in prop "items". It is not enough that the
  // ids are the same. Therefore, we must adjust the labels in "items" if they have
  // been modified in the "selectedItemsArray".
  var multiSelectItems = formatDataItemsForDropdown(dataItems).map(function (item) {
    var _selectedItemsArray$f, _selectedItemsArray$f2;
    return _objectSpread(_objectSpread({}, item), {}, {
      label: (_selectedItemsArray$f = (_selectedItemsArray$f2 = selectedItemsArray.find(function (selected) {
        return selected.dataSourceId === item.id;
      })) === null || _selectedItemsArray$f2 === void 0 ? void 0 : _selectedItemsArray$f2.label) !== null && _selectedItemsArray$f !== void 0 ? _selectedItemsArray$f : item.label
    });
  });
  var handleEditButton = React.useCallback(/*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee(dataItem) {
      var dataItemWithMetaData, aggregationMethods;
      return _regeneratorRuntime__default.default.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            dataItemWithMetaData = dataItems === null || dataItems === void 0 ? void 0 : dataItems.find(function (_ref5) {
              var dataItemId = _ref5.dataItemId;
              return dataItemId === dataItem.dataSourceId;
            }); // Call back function for on click of edit button
            /* istanbul ignore else */
            if (!onEditDataItem) {
              _context.next = 6;
              break;
            }
            _context.next = 4;
            return onEditDataItem(cardConfig, dataItem, dataItemWithMetaData);
          case 4:
            aggregationMethods = _context.sent;
            if (!isEmpty(aggregationMethods)) {
              dataItemWithMetaData.aggregationMethods = aggregationMethods;
            }
          case 6:
            // need to reset the card to include the latest dataSection
            setEditDataItem(_objectSpread(_objectSpread({}, dataItemWithMetaData), dataItem));
            setShowEditor(true);
          case 8:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref4.apply(this, arguments);
    };
  }(), [cardConfig, onEditDataItem, dataItems]);
  var handleRemoveButton = React.useCallback(function (selectedItem) {
    var newArray = selectedItemsArray.filter(function (item) {
      return item.dataSourceId !== selectedItem.dataSourceId;
    });
    onChange({
      attributes: newArray
    });
  }, [selectedItemsArray, onChange]);
  var generateListItems = React.useCallback(function (data) {
    var _data$filter;
    var isHierarchy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return data === null || data === void 0 || (_data$filter = data.filter(function (dataItem) {
      return HierarchyDataFormItems.isHierarchyDataItem(dataItem) === isHierarchy;
    })) === null || _data$filter === void 0 ? void 0 : _data$filter.map(function (dataItem) {
      return {
        id: dataItem.dataSourceId,
        content: {
          value: dataItem.label,
          rowActions: function rowActions() {
            return [/*#__PURE__*/React__default.default.createElement(Button, {
              key: "data-item-".concat(dataItem.dataSourceId),
              renderIcon: iconsReact.Edit,
              hasIconOnly: true,
              kind: "ghost",
              size: "sm",
              onClick: function onClick() {
                return handleEditButton(dataItem);
              },
              iconDescription: mergedI18n.edit,
              tooltipPosition: "left",
              tooltipAlignment: "center"
            }), /*#__PURE__*/React__default.default.createElement(Button, {
              key: "data-item-".concat(dataItem.dataSourceId, "_remove"),
              renderIcon: iconsReact.MisuseOutline,
              hasIconOnly: true,
              kind: "ghost",
              size: "sm",
              onClick: function onClick() {
                return handleRemoveButton(dataItem);
              },
              iconDescription: mergedI18n.remove,
              tooltipPosition: "left",
              tooltipAlignment: "center"
            })];
          }
        }
      };
    });
  }, [handleEditButton, handleRemoveButton, mergedI18n.edit, mergedI18n.remove]);
  var dataListItems = React.useMemo(function () {
    return generateListItems(selectedItemsArray);
  }, [selectedItemsArray, generateListItems]);
  var hierarchyDataListItems = React.useMemo(function () {
    return generateListItems(selectedItemsArray, true);
  }, [selectedItemsArray, generateListItems]);
  return /*#__PURE__*/React__default.default.createElement("div", {
    "data-testid": testID || testId
  }, /*#__PURE__*/React__default.default.createElement(DataSeriesFormItemModal, {
    isLarge: true,
    cardConfig: cardConfig,
    showEditor: showEditor,
    setShowEditor: setShowEditor,
    editDataItem: editDataItem,
    setEditDataItem: setEditDataItem,
    setEditDataSeries: setEditDataItem,
    availableDimensions: availableDimensions,
    onChange: onChange,
    i18n: mergedI18n,
    actions: actions,
    options: {
      hasColorDropdown: false,
      hasUnit: true,
      hasDecimalPlacesDropdown: true,
      hasThresholds: true,
      hasTooltip: false
    }
  }), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, /*#__PURE__*/React__default.default.createElement(react.MultiSelect
  // need to re-gen if multiSelectItems changes (i.e. the label)
  , {
    key: "".concat(multiSelectItems.map(function (item) {
      return item.label;
    }).join('')),
    id: "".concat(cardConfig.id, "_dataSourceIds"),
    label: mergedI18n.selectDataItemsText,
    direction: "bottom",
    selectedItems: formatDataItemsForDropdown(selectedItemsArray),
    items: multiSelectItems,
    light: true,
    onChange: handleSelectionChange,
    titleText: mergedI18n.dataItemText,
    translateWithId: translateWithId,
    "data-testid": "".concat(testId, "-multiselect")
  })), /*#__PURE__*/React__default.default.createElement(List.default
  // need to force an empty "empty state"
  , {
    emptyState: /*#__PURE__*/React__default.default.createElement("div", null),
    testId: "".concat(testId, "-data-source-list"),
    title: "",
    items: dataListItems
  }), /*#__PURE__*/React__default.default.createElement(HierarchyDataFormItems.default, {
    cardConfig: cardConfig,
    hierarchyDataItemListItems: hierarchyDataListItems,
    handleHierarchyDataItemChange: handleHierarchyDataItemChange,
    i18n: i18n,
    actions: actions
  }));
};
HotspotEditorDataSourceTab.propTypes = propTypes;
HotspotEditorDataSourceTab.defaultProps = defaultProps;
HotspotEditorDataSourceTab.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "HotspotEditorDataSourceTab",
  "props": {
    "i18n": {
      "defaultValue": {
        "value": "{\n  selectDataItemsText: 'Select data items',\n  dataItemText: 'Data items',\n  edit: 'Edit',\n  remove: 'Remove',\n  dataItemEditorDataItemTitle: 'Data items',\n  dataItemEditorDataItemCustomLabel: 'Custom label',\n  dataItemEditorDataItemUnit: 'Unit',\n  dataItemEditorDataItemFilter: 'Data filter',\n  dataItemEditorDataItemThresholds: 'Thresholds',\n  dataItemEditorDataItemAddThreshold: 'Add threshold',\n  primaryButtonLabelText: 'Update',\n  secondaryButtonLabelText: 'Cancel',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "selectDataItemsText": {
            "name": "string",
            "required": false
          },
          "dataItemText": {
            "name": "string",
            "required": false
          },
          "edit": {
            "name": "string",
            "required": false
          },
          "remove": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemCustomLabel": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemUnit": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemFilter": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemThresholds": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemAddThreshold": {
            "name": "string",
            "required": false
          },
          "primaryButtonLabelText": {
            "name": "string",
            "required": false
          },
          "secondaryButtonLabelText": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "dataItems": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "An array of data source items that can be selected for the specified hotspot",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "dataSourceId": {
              "name": "string",
              "required": false
            },
            "label": {
              "name": "string",
              "required": false
            }
          }
        }
      },
      "required": false
    },
    "availableDimensions": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "An object where the keys are available dimensions and the values are the values available for those dimensions\n ex: { manufacturer: ['Rentech', 'GHI Industries'], deviceid: ['73000', '73001', '73002'] }",
      "type": {
        "name": "shape",
        "value": {}
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'HotspotEditorDataSourceTab'",
        "computed": false
      },
      "description": "Id that can be used for testing",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "actions": {
      "defaultValue": {
        "value": "defaultDashboardEditorActionsProps",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "custom",
        "raw": "DashboardEditorActionsPropTypes"
      },
      "required": false
    },
    "hotspot": {
      "description": "The hotspot for which the data source settings should be changed.",
      "type": {
        "name": "shape",
        "value": {
          "content": {
            "name": "shape",
            "value": {
              "attributes": {
                "name": "arrayOf",
                "value": {
                  "name": "object"
                },
                "required": false
              }
            },
            "required": false
          }
        }
      },
      "required": true
    },
    "cardConfig": {
      "description": "This prop is mainly needed since the HotspotEditorDataSourceTab internally makes\nuse of DataSeriesFormItemModal which has its API designed around the card config",
      "type": {
        "name": "shape",
        "value": {
          "id": {
            "name": "string",
            "required": false
          },
          "title": {
            "name": "string",
            "required": false
          },
          "size": {
            "name": "string",
            "required": false
          },
          "type": {
            "name": "string",
            "required": false
          },
          "content": {
            "name": "shape",
            "value": {
              "alt": {
                "name": "string",
                "required": false
              },
              "src": {
                "name": "string",
                "required": false
              },
              "image": {
                "name": "string",
                "required": false
              },
              "hideMinimap": {
                "name": "bool",
                "required": false
              },
              "hideHotspots": {
                "name": "bool",
                "required": false
              },
              "hideZoomControls": {
                "name": "bool",
                "required": false
              },
              "id": {
                "name": "string",
                "required": false
              }
            },
            "required": false
          },
          "description": {
            "name": "string",
            "required": false
          },
          "values": {
            "name": "shape",
            "value": {
              "hotspots": {
                "name": "arrayOf",
                "value": {
                  "name": "object"
                },
                "required": false
              }
            },
            "required": false
          }
        }
      },
      "required": true
    },
    "translateWithId": {
      "description": "Callback i18n function for translating ListBoxMenuIcon SVG title in the MultiSelect component",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "onChange": {
      "description": "callback when image input value changes",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "testID": {
      "description": "",
      "type": {
        "name": "custom",
        "raw": "deprecate(\n  PropTypes.string,\n  `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
      },
      "required": false
    }
  }
};
var HotspotEditorDataSourceTab$1 = HotspotEditorDataSourceTab;

exports.default = HotspotEditorDataSourceTab$1;
exports.formatDataItemsForDropdown = formatDataItemsForDropdown;
