"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.Chart = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _styles = require("@material-ui/core/styles");

var _classnames = _interopRequireDefault(require("classnames"));

var _debug = _interopRequireDefault(require("debug"));

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var _plot = require("../plot");

var _configUi = require("../config-ui");

var _translator = _interopRequireDefault(require("../translator"));

var _grid = _interopRequireDefault(require("./grid"));

var _axes = _interopRequireDefault(require("./axes"));

var _utils = require("./utils");

var _chartTypes = _interopRequireDefault(require("./chart-types"));

var _actionsButton = _interopRequireDefault(require("./actions-button"));

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var translator = _translator["default"].translator;
var log = (0, _debug["default"])('pie-lib:charts:chart');

var Chart = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(Chart, _React$Component);

  var _super = _createSuper(Chart);

  function Chart(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Chart);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", {
      charts: [_chartTypes["default"].Bar(), _chartTypes["default"].Histogram(), _chartTypes["default"].LineDot(), _chartTypes["default"].LineCross(), _chartTypes["default"].DotPlot(), _chartTypes["default"].LinePlot()],
      autoFocus: false
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleAlertDialog", function (open, callback) {
      return _this.setState({
        dialog: {
          open: open
        }
      }, callback);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getChart", function () {
      var charts = _this.props.charts || _this.state.charts;
      var chartType = _this.props.chartType;
      var ChartComponent = null;
      var chart = null;

      if (chartType) {
        chart = charts && charts.find(function (chart) {
          return chart.type === chartType;
        });
        ChartComponent = chart && chart.Component;
      } else {
        chart = charts && charts[0];
        ChartComponent = chart && chart.Component;
        chartType = chart && chart.type;
      }

      return {
        type: chartType,
        ChartComponent: ChartComponent
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeData", function (data) {
      var onDataChange = _this.props.onDataChange;
      onDataChange(data);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeCategory", function (index, newCategory) {
      var integerIndex = parseInt(index, 10);

      if (integerIndex >= 0) {
        var _this$props = _this.props,
            data = _this$props.data,
            onDataChange = _this$props.onDataChange;
        data[integerIndex] = _objectSpread(_objectSpread({}, data[integerIndex]), newCategory);
        onDataChange(data);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "addCategory", function () {
      var _this$props2 = _this.props,
          onDataChange = _this$props2.onDataChange,
          data = _this$props2.data,
          categoryDefaultLabel = _this$props2.categoryDefaultLabel,
          defineChart = _this$props2.defineChart,
          categoryDefaults = _this$props2.categoryDefaults,
          language = _this$props2.language;

      if ((data || []).length > 19) {
        _this.setState({
          dialog: {
            open: true,
            title: translator.t('common:warning', {
              lng: language
            }),
            text: translator.t('charting.reachedLimit_other', {
              count: 20,
              lng: language
            }),
            onConfirm: function onConfirm() {
              return _this.handleAlertDialog(false);
            }
          }
        });
      } else {
        _this.setState({
          autoFocus: true
        });

        onDataChange([].concat((0, _toConsumableArray2["default"])(data), [{
          inDefineChart: defineChart,
          label: categoryDefaultLabel || translator.t('charting.newLabel', {
            lng: language
          }),
          value: 0,
          deletable: true,
          editable: categoryDefaults ? categoryDefaults === null || categoryDefaults === void 0 ? void 0 : categoryDefaults.editable : true,
          interactive: categoryDefaults ? categoryDefaults === null || categoryDefaults === void 0 ? void 0 : categoryDefaults.interactive : true
        }]));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "deleteCategory", function (index) {
      var _this$props3 = _this.props,
          data = _this$props3.data,
          onDataChange = _this$props3.onDataChange;

      if (typeof index !== 'number' || index < 0) {
        return;
      }

      if (data && data.length > 0) {
        onDataChange(data.filter(function (_, i) {
          return i !== index;
        }));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getFilteredCategories", function () {
      var _this$props4 = _this.props,
          data = _this$props4.data,
          defineChart = _this$props4.defineChart;
      return data ? data.map(function (d) {
        return _objectSpread(_objectSpread({}, d), {}, {
          deletable: defineChart || d.deletable
        });
      }) : [];
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "resetAutoFocus", function () {
      _this.setState({
        autoFocus: false
      });
    });
    _this.state = {
      dialog: {
        open: false
      },
      actionsAnchorEl: null
    };
    _this.maskUid = _this.generateMaskId();
    return _this;
  }

  (0, _createClass2["default"])(Chart, [{
    key: "generateMaskId",
    value: function generateMaskId() {
      return 'chart-' + (Math.random() * 10000).toFixed();
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props5 = this.props,
          classes = _this$props5.classes,
          className = _this$props5.className,
          _this$props5$domain = _this$props5.domain,
          domain = _this$props5$domain === void 0 ? {} : _this$props5$domain,
          _this$props5$range = _this$props5.range,
          range = _this$props5$range === void 0 ? {} : _this$props5$range,
          chartingOptions = _this$props5.chartingOptions,
          size = _this$props5.size,
          title = _this$props5.title,
          onChangeTitle = _this$props5.onChangeTitle,
          onChangeLabels = _this$props5.onChangeLabels,
          labelsPlaceholders = _this$props5.labelsPlaceholders,
          titlePlaceholder = _this$props5.titlePlaceholder,
          addCategoryEnabled = _this$props5.addCategoryEnabled,
          changeInteractiveEnabled = _this$props5.changeInteractiveEnabled,
          changeEditableEnabled = _this$props5.changeEditableEnabled,
          showPixelGuides = _this$props5.showPixelGuides,
          error = _this$props5.error,
          _this$props5$mathMlOp = _this$props5.mathMlOptions,
          mathMlOptions = _this$props5$mathMlOp === void 0 ? {} : _this$props5$mathMlOp,
          language = _this$props5.language,
          labelsCharactersLimit = _this$props5.labelsCharactersLimit;
      var chartType = this.props.chartType;
      var dialog = this.state.dialog;
      var defineChart = this.props.defineChart || false;

      var _ref = size || {},
          width = _ref.width,
          height = _ref.height;

      var labels = {
        left: (range === null || range === void 0 ? void 0 : range.label) || '',
        bottom: (domain === null || domain === void 0 ? void 0 : domain.label) || ''
      };

      var _this$getChart = this.getChart(),
          ChartComponent = _this$getChart.ChartComponent;

      var categories = this.getFilteredCategories();
      var correctValues = (0, _utils.getDomainAndRangeByChartType)(domain, range, chartType);

      var _getGridLinesAndAxisB = (0, _utils.getGridLinesAndAxisByChartType)(correctValues.range, chartType),
          verticalLines = _getGridLinesAndAxisB.verticalLines,
          horizontalLines = _getGridLinesAndAxisB.horizontalLines,
          leftAxis = _getGridLinesAndAxisB.leftAxis;

      var common = {
        graphProps: (0, _plot.createGraphProps)(correctValues.domain, correctValues.range, size, function () {
          return _this2.rootNode;
        })
      };
      log('[render] common:', common);
      var maskSize = {
        x: -10,
        y: -75,
        width: width + 20,
        height: height + 80
      };
      var scale = common.graphProps.scale;
      var xBand = (0, _utils.dataToXBand)(scale.x, categories, width, chartType);

      if (!ChartComponent) {
        return null;
      }

      var bandWidth = xBand.bandwidth(); // for chartType "line", bandWidth will be 0, so we have to calculate it

      var barWidth = bandWidth || scale.x(correctValues.domain.max) / categories.length;
      var increaseHeight = defineChart ? 160 : 60; // if there are many categories, we have to rotate their names in order to fit
      // and we have to add extra value on top of some items

      var top = (0, _utils.getTopPadding)(barWidth);
      var rootCommon = (0, _cloneDeep["default"])(common);
      rootCommon.graphProps.size.height += top + increaseHeight;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames["default"])(classes.chart, classes.chartBox, className)
      }, /*#__PURE__*/_react["default"].createElement(_plot.Root, (0, _extends2["default"])({
        title: title,
        onChangeTitle: onChangeTitle,
        disabledTitle: !defineChart,
        showTitle: true,
        showLabels: true,
        labels: labels,
        onChangeLabels: onChangeLabels,
        labelsPlaceholders: labelsPlaceholders,
        titlePlaceholder: titlePlaceholder,
        defineChart: defineChart,
        disabledLabels: !defineChart,
        isChart: true,
        showPixelGuides: showPixelGuides,
        rootRef: function rootRef(r) {
          return _this2.rootNode = r;
        },
        mathMlOptions: mathMlOptions,
        labelsCharactersLimit: labelsCharactersLimit
      }, rootCommon), /*#__PURE__*/_react["default"].createElement(_grid["default"], (0, _extends2["default"])({}, common, {
        xBand: xBand,
        rowTickValues: horizontalLines,
        columnTickValues: verticalLines
      })), /*#__PURE__*/_react["default"].createElement(_axes["default"], (0, _extends2["default"])({
        autoFocus: this.state.autoFocus,
        onAutoFocusUsed: this.resetAutoFocus
      }, common, {
        defineChart: defineChart,
        categories: categories,
        xBand: xBand,
        leftAxis: leftAxis,
        onChange: this.changeData,
        onChangeCategory: this.changeCategory,
        chartingOptions: chartingOptions,
        changeInteractiveEnabled: changeInteractiveEnabled,
        changeEditableEnabled: changeEditableEnabled,
        top: top,
        error: error
      })), addCategoryEnabled ? /*#__PURE__*/_react["default"].createElement("foreignObject", {
        x: width,
        y: height - 16,
        width: width,
        height: height
      }, /*#__PURE__*/_react["default"].createElement("div", {
        xmlns: "http://www.w3.org/1999/xhtml",
        style: {
          display: 'flex',
          justifyContent: 'flex-start'
        }
      }, /*#__PURE__*/_react["default"].createElement(_actionsButton["default"], {
        categories: categories,
        addCategory: this.addCategory,
        deleteCategory: this.deleteCategory,
        language: language
      }))) : null, /*#__PURE__*/_react["default"].createElement("mask", {
        id: "".concat(this.maskUid)
      }, /*#__PURE__*/_react["default"].createElement("rect", (0, _extends2["default"])({}, maskSize, {
        fill: "white"
      }))), /*#__PURE__*/_react["default"].createElement("g", {
        id: "marks",
        mask: "url('#".concat(this.maskUid, "')")
      }, /*#__PURE__*/_react["default"].createElement(ChartComponent, (0, _extends2["default"])({}, common, {
        data: categories,
        height: rootCommon.graphProps.size.height,
        defineChart: defineChart,
        onChange: this.changeData,
        onChangeCategory: this.changeCategory
      })))), /*#__PURE__*/_react["default"].createElement(_configUi.AlertDialog, {
        open: dialog.open,
        title: dialog.title,
        text: dialog.text,
        onClose: dialog.onClose,
        onConfirm: dialog.onConfirm
      }));
    }
  }]);
  return Chart;
}(_react["default"].Component);

exports.Chart = Chart;
(0, _defineProperty2["default"])(Chart, "propTypes", {
  classes: _propTypes["default"].object.isRequired,
  className: _propTypes["default"].string,
  chartType: _propTypes["default"].string.isRequired,
  size: _propTypes["default"].shape({
    width: _propTypes["default"].number,
    height: _propTypes["default"].number
  }),
  domain: _propTypes["default"].shape({
    label: _propTypes["default"].string,
    min: _propTypes["default"].number,
    max: _propTypes["default"].number,
    axisLabel: _propTypes["default"].string
  }),
  data: _propTypes["default"].arrayOf(_propTypes["default"].shape({
    label: _propTypes["default"].string,
    value: _propTypes["default"].number
  })),
  range: _propTypes["default"].shape({
    label: _propTypes["default"].string,
    min: _propTypes["default"].number,
    max: _propTypes["default"].number,
    step: _propTypes["default"].number,
    labelStep: _propTypes["default"].number,
    axisLabel: _propTypes["default"].string
  }),
  charts: _propTypes["default"].array,
  labelsPlaceholders: _propTypes["default"].object,
  title: _propTypes["default"].string,
  titlePlaceholder: _propTypes["default"].string,
  onDataChange: _propTypes["default"].func,
  onChangeLabels: _propTypes["default"].func,
  onChangeTitle: _propTypes["default"].func,
  error: _propTypes["default"].any,
  addCategoryEnabled: _propTypes["default"].bool,
  showPixelGuides: _propTypes["default"].bool,
  categoryDefaultLabel: _propTypes["default"].string,
  categoryDefaults: _propTypes["default"].object,
  defineChart: _propTypes["default"].bool,
  theme: _propTypes["default"].object,
  chartingOptions: _propTypes["default"].object,
  changeInteractiveEnabled: _propTypes["default"].bool,
  changeEditableEnabled: _propTypes["default"].bool,
  language: _propTypes["default"].string,
  mathMlOptions: _propTypes["default"].object,
  labelsCharactersLimit: _propTypes["default"].number
});
(0, _defineProperty2["default"])(Chart, "defaultProps", {
  size: {
    width: 480,
    height: 480
  }
});

var styles = function styles(theme) {
  return {
    graphBox: {
      transform: 'translate(60px, 35px)'
    },
    svg: {
      overflow: 'visible'
    },
    chartBox: {
      width: 'min-content'
    }
  };
};

var _default = (0, _styles.withStyles)(styles, {
  withTheme: true
})(Chart);

exports["default"] = _default;
//# sourceMappingURL=chart.js.map