'use strict';

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

var _extends = require('@babel/runtime/helpers/extends');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var defaultsDeep = require('../../node_modules/lodash-es/defaultsDeep.js');
var isEmpty = require('../../node_modules/lodash-es/isEmpty.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.fill.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.iterator.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.object.from-entries.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/es.object.values.js');
require('core-js/modules/web.dom-collections.for-each.js');
require('core-js/modules/web.dom-collections.iterator.js');
var React = require('react');
var chartsReact = require('@carbon/charts-react');
var classnames = require('classnames');
var CardPropTypes = require('../../constants/CardPropTypes.js');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var Settings = require('../../constants/Settings.js');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var componentUtilityFunctions = require('../../utils/componentUtilityFunctions.js');
var Card = require('../Card/Card.js');
var Table = require('../Table/Table.js');

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

var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var _excluded = ["children", "content", "i18n", "id", "isExpanded", "isEditable", "isLoading", "isResizable", "overrides", "size", "title", "values", "testID", "testId"];
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 getColor = function getColor(colors, datasetLabel, label, data, defaultStrokeColor) {
  return colors ? colors[datasetLabel] : defaultStrokeColor;
};
var generateSampleData = function generateSampleData(sampleSlicesCount, groupDataSourceId) {
  var sample = Array(sampleSlicesCount).fill(0).map(function (obj, index) {
    return _defineProperty__default.default(_defineProperty__default.default({}, groupDataSourceId, "Sample ".concat(index)), "value", Math.floor(Math.random() * 10) + 1);
  });
  return sample;
};
var getColorsForSampleData = function getColorsForSampleData(colorsProp, sampleValues, groupDataSourceId) {
  var colorValues = Object.values(colorsProp);
  var sampleColors = Object.create(null);
  sampleValues.forEach(function (sliceData, index) {
    var key = sliceData[groupDataSourceId];
    sampleColors[key] = colorValues[index];
  });
  return sampleColors;
};
var generateTableRows = function generateTableRows(id, values, groupDataSourceId) {
  var tableRowValues = Object.fromEntries(values.map(function (_ref2) {
    var value = _ref2.value,
      columnName = _ref2[groupDataSourceId];
    return [columnName, value];
  }));
  return isEmpty(values) ? [] : [{
    id: "".concat(id, "-table-row"),
    values: tableRowValues
  }];
};
var generateTableColumns = function generateTableColumns(values, groupDataSourceId) {
  return values.map(function (slice) {
    return {
      id: slice[groupDataSourceId],
      name: slice[groupDataSourceId]
    };
  });
};

/**
 * Formats and maps the colors to their corresponding datasets in the carbon pie chart card expected format
 * @param {Array} values, an array of group, value objects for each pie label
 * @param {string} groupDataSourceId, the group id to use to find the value
 * @param {Object} colors an object of colors
 * @returns {Object} colors - formatted
 */
var formatColors = function formatColors(values, groupDataSourceId, colors) {
  var formattedColors = {
    scale: {}
  };
  if (Array.isArray(values)) {
    values.forEach(function (value, index) {
      formattedColors.scale[value[groupDataSourceId]] = colors !== null && colors !== void 0 && colors[value[groupDataSourceId]] ? colors[value[groupDataSourceId]] // look to find a matching color entry in our colors otherwise use defaults
      : CardPropTypes.CHART_COLORS[index % CardPropTypes.CHART_COLORS.length];
    });
  } else if (!isEmpty(values)) {
    // values is an object
    Object.keys(values).forEach(function (key, index) {
      formattedColors.scale[key] = colors !== null && colors !== void 0 && colors[key] ? colors === null || colors === void 0 ? void 0 : colors[key] : CardPropTypes.CHART_COLORS[index % CardPropTypes.CHART_COLORS.length];
    });
  }
  return formattedColors;
};
var propTypes = _objectSpread(_objectSpread({}, CardPropTypes.CardPropTypes), CardPropTypes.PieCardPropTypes);
var defaultProps = {
  size: LayoutConstants.CARD_SIZES.MEDIUMWIDE,
  i18n: {
    noDataLabel: 'No data'
  },
  content: {
    colors: undefined,
    groupDataSourceId: 'group',
    legendAlignment: 'left',
    legendPosition: 'bottom',
    truncation: {
      type: 'end_line',
      threshold: 20,
      numCharacter: 20
    }
  },
  overrides: undefined
};
var PieChartCard = function PieChartCard(_ref3) {
  var _overrides$card, _overrides$pieChart, _overrides$table, _overrides$card2, _overrides$pieChart2, _overrides$table2;
  var children = _ref3.children,
    content = _ref3.content,
    i18n = _ref3.i18n,
    id = _ref3.id,
    isExpanded = _ref3.isExpanded,
    isEditable = _ref3.isEditable,
    isLoading = _ref3.isLoading,
    isResizable = _ref3.isResizable,
    overrides = _ref3.overrides,
    sizeProp = _ref3.size,
    titleProp = _ref3.title,
    initialValuesProp = _ref3.values,
    testID = _ref3.testID,
    testId = _ref3.testId,
    others = _objectWithoutProperties__default.default(_ref3, _excluded);
  // need to deep merge the nested content default props as default props only uses a shallow merge natively
  var contentWithDefaults = React.useMemo(function () {
    return defaultsDeep({}, content, defaultProps.content);
  }, [content]);
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var _handleCardVariables = cardUtilityFunctions.handleCardVariables(titleProp, contentWithDefaults, initialValuesProp, others),
    title = _handleCardVariables.title,
    _handleCardVariables$ = _handleCardVariables.content,
    colorsProp = _handleCardVariables$.colors,
    customTooltip = _handleCardVariables$.customTooltip,
    groupDataSourceId = _handleCardVariables$.groupDataSourceId,
    labelsFormatter = _handleCardVariables$.labelsFormatter,
    legendAlignment = _handleCardVariables$.legendAlignment,
    legendPosition = _handleCardVariables$.legendPosition,
    truncation = _handleCardVariables$.truncation,
    valuesProp = _handleCardVariables.values;
  var values = React.useMemo(function () {
    var sampleSlicesCount = colorsProp ? Object.keys(colorsProp).length : 4;
    return isEditable ? generateSampleData(sampleSlicesCount, groupDataSourceId) : valuesProp;
  }, [colorsProp, groupDataSourceId, valuesProp, isEditable]);
  var colors = isEditable && colorsProp ? getColorsForSampleData(colorsProp, values, groupDataSourceId) : colorsProp;
  var resizeHandles = isResizable ? cardUtilityFunctions.getResizeHandles(children) : [];
  var chartProps = {
    // Changes to some options does not update the chart so we modify the key for these
    // specific props, please see https://github.com/carbon-design-system/carbon-charts/issues/817
    key: "pie-chart-".concat(groupDataSourceId, "-").concat(legendPosition, "-").concat(isEditable, "-").concat(sizeProp),
    data: values,
    options: {
      accessibility: true,
      animations: false,
      data: {
        groupMapsTo: groupDataSourceId,
        loading: isLoading
      },
      color: formatColors(values, groupDataSourceId, colors),
      getFillColor: function getFillColor() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        return getColor.apply(void 0, [colors].concat(args));
      },
      getStrokeColor: function getStrokeColor() {
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        return getColor.apply(void 0, [colors].concat(args));
      },
      legend: {
        alignment: legendAlignment,
        position: legendPosition,
        enabled: values.length > 1,
        clickable: !isEditable,
        truncation: truncation
      },
      pie: {
        labels: {
          formatter: labelsFormatter
        },
        alignment: 'center'
      },
      resizable: true,
      tooltip: {
        customHTML: customTooltip
      },
      toolbar: {
        enabled: false
      }
    }
  };
  var tableProps = {
    // TODO: remove deprecated 'testID' in v3.
    'data-testid': "".concat(testID || testId, "-table"),
    id: "".concat(id, "-table"),
    className: "".concat(iotPrefix, "--pie-chart-card--stateful-table"),
    columns: generateTableColumns(values, groupDataSourceId),
    data: generateTableRows(id, values, groupDataSourceId),
    actions: {
      table: {},
      toolbar: {
        onDownloadCSV: function onDownloadCSV(tableData) {
          return componentUtilityFunctions.csvDownloadHandler(tableData, title);
        }
      }
    },
    view: {
      table: {
        emptyState: {
          message: mergedI18n.noDataLabel
        }
      }
    },
    i18n: mergedI18n
  };
  var size = cardUtilityFunctions.increaseSmallCardSize(sizeProp, 'PieChartCard');
  var isAllValuesEmpty = isEmpty(values);
  var MyCard = (overrides === null || overrides === void 0 || (_overrides$card = overrides.card) === null || _overrides$card === void 0 ? void 0 : _overrides$card.component) || Card.default;
  var MyPieChart = (overrides === null || overrides === void 0 || (_overrides$pieChart = overrides.pieChart) === null || _overrides$pieChart === void 0 ? void 0 : _overrides$pieChart.component) || chartsReact.PieChart;
  var MyTable = (overrides === null || overrides === void 0 || (_overrides$table = overrides.table) === null || _overrides$table === void 0 ? void 0 : _overrides$table.component) || Table.default;
  return /*#__PURE__*/React__default.default.createElement(MyCard, _extends__default.default({
    title: title,
    className: "".concat(iotPrefix, "--pie-chart-card"),
    size: size,
    i18n: mergedI18n,
    id: id,
    isExpanded: isExpanded
    // The Card has its own isEmpty rendering, but if the data is being loaded we want to use
    // the loading skeleton from the PieChart instead.
    ,
    isEmpty: isAllValuesEmpty && !isLoading,
    isEditable: isEditable,
    isResizable: isResizable,
    resizeHandles: resizeHandles
    // TODO: remove deprecated 'testID' in v3.
    ,
    testId: testID || testId
  }, others, overrides === null || overrides === void 0 || (_overrides$card2 = overrides.card) === null || _overrides$card2 === void 0 ? void 0 : _overrides$card2.props), isLoading || !isAllValuesEmpty ? /*#__PURE__*/React__default.default.createElement("div", {
    className: classnames__default.default("".concat(iotPrefix, "--pie-chart-container"), _defineProperty__default.default({}, "".concat(iotPrefix, "--pie-chart-container__expanded"), isExpanded))
  }, /*#__PURE__*/React__default.default.createElement(MyPieChart, _extends__default.default({}, chartProps, componentUtilityFunctions.getOverrides(overrides === null || overrides === void 0 || (_overrides$pieChart2 = overrides.pieChart) === null || _overrides$pieChart2 === void 0 ? void 0 : _overrides$pieChart2.props, chartProps))), isExpanded && !isLoading ? /*#__PURE__*/React__default.default.createElement(MyTable, _extends__default.default({}, tableProps, componentUtilityFunctions.getOverrides(overrides === null || overrides === void 0 || (_overrides$table2 = overrides.table) === null || _overrides$table2 === void 0 ? void 0 : _overrides$table2.props, tableProps))) : null) : null, resizeHandles);
};
PieChartCard.propTypes = propTypes;
PieChartCard.defaultProps = defaultProps;
PieChartCard.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "PieChartCard",
  "props": {
    "size": {
      "defaultValue": {
        "value": "CARD_SIZES.MEDIUMWIDE",
        "computed": true
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  noDataLabel: 'No data',\n}",
        "computed": false
      },
      "required": false
    },
    "content": {
      "defaultValue": {
        "value": "{\n  colors: undefined,\n  groupDataSourceId: 'group',\n  legendAlignment: 'left',\n  legendPosition: 'bottom',\n  truncation: {\n    type: 'end_line',\n    threshold: 20,\n    numCharacter: 20,\n  },\n}",
        "computed": false
      },
      "required": false
    },
    "overrides": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "required": false
    }
  },
  "composes": ["../../constants/CardPropTypes"]
};
var PieChartCard$1 = PieChartCard;

exports.default = PieChartCard$1;
exports.formatColors = formatColors;
