'use strict';

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

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isEmpty = require('../../../../../node_modules/lodash-es/isEmpty.js');
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.find-index.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.sort.js');
require('core-js/modules/es.number.parse-int.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 update = require('immutability-helper');
var react = require('@carbon/react');
var Settings = require('../../../../../constants/Settings.js');
var CardPropTypes = require('../../../../../constants/CardPropTypes.js');

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

var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var update__default = /*#__PURE__*/_interopDefault(update);

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 = {
  /** card data value */
  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: CardPropTypes.TableCardPropTypes.content
  }),
  /** Callback function when form data changes */
  onChange: PropTypes__default.default.func.isRequired,
  i18n: PropTypes__default.default.shape({
    rowsPerPage: PropTypes__default.default.string,
    sortBy: PropTypes__default.default.string,
    sortByDataItem: PropTypes__default.default.string,
    ascending: PropTypes__default.default.string,
    descending: PropTypes__default.default.string,
    showHeader: PropTypes__default.default.string,
    allowNavigation: PropTypes__default.default.string
  }),
  /** Callback function to translate common ids */
  translateWithId: PropTypes__default.default.func.isRequired,
  /** 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({})
};
var defaultProps = {
  cardConfig: {},
  i18n: {
    rowsPerPage: 'Rows per page',
    sortBy: 'Sort by',
    sortByTitle: 'Sort by data item',
    ascending: 'Ascending',
    descending: 'Descending',
    showHeader: 'Show table header',
    allowNavigation: 'Allow navigation to assets',
    maximumDataPoints: 'Maximum data points'
  },
  availableDimensions: {}
};

/**
 * Helper function to update the column sort
 * @param {array} columns existing array of columns
 * @param {*} columnDataSourceId
 * @param {*} sortDirection
 * @returns {array} newColumns returned with updated sort
 */
var updateColumnSort = function updateColumnSort(columns, sortDataSourceId, sortDirection) {
  var existingColumnSort = columns.find(function (col) {
    return col.sort;
  });
  if (sortDataSourceId === (existingColumnSort === null || existingColumnSort === void 0 ? void 0 : existingColumnSort.dataSourceId) && sortDirection !== (existingColumnSort === null || existingColumnSort === void 0 ? void 0 : existingColumnSort.sort)) {
    // update existing column sort to the new sort direction
    return update__default.default(columns, {
      $splice: [[columns.findIndex(function (col) {
        return col.sort;
      }), 1, _objectSpread(_objectSpread({}, existingColumnSort), {}, {
        sort: sortDirection
      })]]
    });
  }
  // Is it a new column sort?
  if (sortDataSourceId !== (existingColumnSort === null || existingColumnSort === void 0 ? void 0 : existingColumnSort.dataSourceId)) {
    var newColumnToSort = columns.find(function (col) {
      return col.dataSourceId === sortDataSourceId;
    });
    return update__default.default(columns, {
      $splice: [].concat(_toConsumableArray__default.default(existingColumnSort ? [[columns.findIndex(function (col) {
        return col.sort;
      }), 1, _objectSpread(_objectSpread({}, existingColumnSort), {}, {
        sort: undefined
      }) // clear the existing sort
      ]] : [[]]), [[
      // update the new column with the new sort direction
      columns.findIndex(function (col) {
        return col.dataSourceId === sortDataSourceId;
      }), 1, _objectSpread(_objectSpread({}, newColumnToSort), {}, {
        sort: sortDirection
      })]])
    });
  }
  // otherwise don't sort anything
  return columns;
};

/**
 * Stateless render component that renders the current settings panel based on the inbound cardConfig prop
 * and calls onChange with the updated cardConfig object every time the user interacts with the form
 */
var TableCardFormSettings = function TableCardFormSettings(_ref) {
  var _cardConfig$content2, _cardConfig$content5, _cardConfig$content6;
  var cardConfig = _ref.cardConfig,
    _onChange = _ref.onChange,
    i18n = _ref.i18n,
    translateWithId = _ref.translateWithId;
  var mergedI18n = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var content = cardConfig.content,
    id = cardConfig.id;
  var baseClassName = "".concat(iotPrefix, "--card-edit-form");
  var dataItems = React.useMemo(function () {
    return Array.isArray(content === null || content === void 0 ? void 0 : content.columns) ? content === null || content === void 0 ? void 0 : content.columns.map(function (column) {
      return column.dataSourceId;
    }) : [];
  }, [content]);

  // figure out if a column has been updated to be the default sort column
  var defaultSortColumn = React.useMemo(function () {
    return Array.isArray(content === null || content === void 0 ? void 0 : content.columns) ? content.columns.find(function (col) {
      return col.sort;
    }) : null;
  }, [content]);

  // updates the sort based on the direction
  var handleSortColumn = React.useCallback(function (sortDirection) {
    var _cardConfig$content;
    return _onChange(update__default.default(cardConfig, {
      content: {
        columns: {
          $set: updateColumnSort(cardConfig === null || cardConfig === void 0 || (_cardConfig$content = cardConfig.content) === null || _cardConfig$content === void 0 ? void 0 : _cardConfig$content.columns, defaultSortColumn === null || defaultSortColumn === void 0 ? void 0 : defaultSortColumn.dataSourceId, sortDirection)
        }
      }
    }));
  }, [cardConfig, defaultSortColumn, _onChange]);
  return /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, !isEmpty(cardConfig === null || cardConfig === void 0 || (_cardConfig$content2 = cardConfig.content) === null || _cardConfig$content2 === void 0 ? void 0 : _cardConfig$content2.columns) ? /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, /*#__PURE__*/React__default.default.createElement(react.Dropdown, {
    id: "".concat(id, "_sort_by_dropdown"),
    titleText: mergedI18n.sortBy,
    direction: "bottom",
    label: mergedI18n.sortBy,
    items: dataItems,
    light: true,
    translateWithId: translateWithId,
    selectedItem: defaultSortColumn === null || defaultSortColumn === void 0 ? void 0 : defaultSortColumn.dataSourceId,
    onChange: function onChange(_ref2) {
      var _cardConfig$content3, _cardConfig$content4;
      var selectedItem = _ref2.selectedItem;
      var existingColumn = cardConfig === null || cardConfig === void 0 || (_cardConfig$content3 = cardConfig.content) === null || _cardConfig$content3 === void 0 ? void 0 : _cardConfig$content3.columns.find(function (col) {
        return col.dataSourceId === selectedItem;
      });
      // default the sort for the newly selected field
      _onChange(update__default.default(cardConfig, {
        content: {
          columns: {
            $set: updateColumnSort(cardConfig === null || cardConfig === void 0 || (_cardConfig$content4 = cardConfig.content) === null || _cardConfig$content4 === void 0 ? void 0 : _cardConfig$content4.columns, selectedItem, (existingColumn === null || existingColumn === void 0 ? void 0 : existingColumn.type) === 'TIMESTAMP' ? 'DESC' : 'ASC')
          }
        }
      }));
    }
  })), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, /*#__PURE__*/React__default.default.createElement(react.RadioButtonGroup, {
    name: "".concat(baseClassName, "--input-radios"),
    onChange: function onChange(evt) {
      return handleSortColumn(evt);
    },
    orientation: "vertical",
    legend: "".concat(mergedI18n.descending),
    labelPosition: "right",
    valueSelected: defaultSortColumn === null || defaultSortColumn === void 0 ? void 0 : defaultSortColumn.sort
  }, /*#__PURE__*/React__default.default.createElement(react.RadioButton, {
    "data-testid": "".concat(baseClassName, "--input-radio1"),
    value: "DESC",
    id: "".concat(baseClassName, "--input-radio-1"),
    labelText: mergedI18n.descending
  }), /*#__PURE__*/React__default.default.createElement(react.RadioButton, {
    "data-testid": "".concat(baseClassName, "--input-radio2"),
    value: "ASC",
    id: "".concat(baseClassName, "--input-radio-2"),
    labelText: mergedI18n.ascending
  })))) : null, /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, /*#__PURE__*/React__default.default.createElement(react.Layer, null, /*#__PURE__*/React__default.default.createElement(react.NumberInput, {
    id: "".concat(id, "_maximum_data_points"),
    label: mergedI18n.maximumDataPoints,
    step: 10,
    min: 0,
    onChange: function onChange(event, _ref3) {
      var value = _ref3.value;
      var maximumDataPoints = Number.parseInt(value, 10);
      _onChange(_objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          maximumDataPoints: maximumDataPoints < 0 ? 0 : maximumDataPoints
        })
      }));
    },
    value: content === null || content === void 0 ? void 0 : content.maximumDataPoints
  }))), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input--toggle-field")
  }, /*#__PURE__*/React__default.default.createElement("span", null, mergedI18n.showHeader), /*#__PURE__*/React__default.default.createElement(react.Toggle, {
    size: "sm",
    "data-testid": "".concat(baseClassName, "--input-toggle1"),
    id: "".concat(baseClassName, "--input-toggle-1"),
    "aria-label": mergedI18n.showHeader,
    labelA: "",
    labelB: "",
    toggled: (_cardConfig$content5 = cardConfig.content) === null || _cardConfig$content5 === void 0 ? void 0 : _cardConfig$content5.showHeader,
    onToggle: function onToggle(bool) {
      return _onChange(_objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          showHeader: bool
        })
      }));
    }
  }))), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input--toggle-field")
  }, /*#__PURE__*/React__default.default.createElement("span", null, mergedI18n.allowNavigation), /*#__PURE__*/React__default.default.createElement(react.Toggle, {
    size: "sm",
    "data-testid": "".concat(baseClassName, "--input-toggle2"),
    id: "".concat(baseClassName, "--input-toggle-2"),
    "aria-label": mergedI18n.allowNavigation,
    labelA: "",
    labelB: "",
    toggled: (_cardConfig$content6 = cardConfig.content) === null || _cardConfig$content6 === void 0 ? void 0 : _cardConfig$content6.allowNavigation,
    onToggle: function onToggle(bool) {
      return _onChange(_objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          allowNavigation: bool
        })
      }));
    }
  }))));
};
TableCardFormSettings.propTypes = propTypes;
TableCardFormSettings.defaultProps = defaultProps;
TableCardFormSettings.__docgenInfo = {
  "description": "Stateless render component that renders the current settings panel based on the inbound cardConfig prop\nand calls onChange with the updated cardConfig object every time the user interacts with the form",
  "methods": [],
  "displayName": "TableCardFormSettings",
  "props": {
    "cardConfig": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "card data value",
      "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": "custom",
            "raw": "TableCardPropTypes.content",
            "required": false
          }
        }
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  rowsPerPage: 'Rows per page',\n  sortBy: 'Sort by',\n  sortByTitle: 'Sort by data item',\n  ascending: 'Ascending',\n  descending: 'Descending',\n  showHeader: 'Show table header',\n  allowNavigation: 'Allow navigation to assets',\n  maximumDataPoints: 'Maximum data points',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "rowsPerPage": {
            "name": "string",
            "required": false
          },
          "sortBy": {
            "name": "string",
            "required": false
          },
          "sortByDataItem": {
            "name": "string",
            "required": false
          },
          "ascending": {
            "name": "string",
            "required": false
          },
          "descending": {
            "name": "string",
            "required": false
          },
          "showHeader": {
            "name": "string",
            "required": false
          },
          "allowNavigation": {
            "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
    },
    "onChange": {
      "description": "Callback function when form data changes",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "translateWithId": {
      "description": "Callback function to translate common ids",
      "type": {
        "name": "func"
      },
      "required": true
    }
  }
};
var TableCardFormSettings$1 = TableCardFormSettings;

exports.default = TableCardFormSettings$1;
exports.updateColumnSort = updateColumnSort;
