"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

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

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

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

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

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

var _renderUi = require("../render-ui");

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

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _chartType = _interopRequireDefault(require("./chart-type"));

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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; }

var resetValues = function resetValues(data, updateModel, range, onChange, model) {
  (data || []).forEach(function (d) {
    var d_value_scaled = Math.round(d.value * 10);
    var range_step_scaled = Math.round(range.step * 10);
    var remainder_scaled = d_value_scaled % range_step_scaled;
    var remainder = remainder_scaled / 10;

    if (d.value > range.max || remainder !== 0) {
      d.value = 0;
    }
  });

  if (updateModel) {
    onChange(_objectSpread(_objectSpread({}, model), {}, {
      data: data
    }));
  }
};

exports.resetValues = resetValues;

var ConfigureChartPanel = function ConfigureChartPanel(props) {
  var classes = props.classes,
      model = props.model,
      onChange = props.onChange,
      chartDimensions = props.chartDimensions,
      _props$gridValues = props.gridValues,
      gridValues = _props$gridValues === void 0 ? {} : _props$gridValues,
      _props$labelValues = props.labelValues,
      labelValues = _props$labelValues === void 0 ? {} : _props$labelValues,
      _props$studentNewCate = props.studentNewCategoryDefaultLabel,
      studentNewCategoryDefaultLabel = _props$studentNewCate === void 0 ? {} : _props$studentNewCate,
      _props$availableChart = props.availableChartTypes,
      availableChartTypes = _props$availableChart === void 0 ? {} : _props$availableChart,
      chartTypeLabel = props.chartTypeLabel;

  var _useState = (0, _react.useState)({
    open: false,
    title: '',
    text: '',
    onClose: null,
    onConfirm: null
  }),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      alertDialog = _useState2[0],
      setAlertDialog = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      open = _useState4[0],
      setOpen = _useState4[1];

  var _useState5 = (0, _react.useState)(''),
      _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
      rangeKey = _useState6[0],
      setRangeKey = _useState6[1];

  var _useState7 = (0, _react.useState)(0),
      _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
      resetValue = _useState8[0],
      setResetValue = _useState8[1];

  var _model$range = model.range,
      range = _model$range === void 0 ? {} : _model$range,
      correctAnswer = model.correctAnswer,
      changeInteractiveEnabled = model.changeInteractiveEnabled,
      changeEditableEnabled = model.changeEditableEnabled;
  var size = model.graph;

  var _ref = chartDimensions || {},
      showInConfigPanel = _ref.showInConfigPanel,
      width = _ref.width,
      height = _ref.height;

  var widthConstraints = {
    min: width !== null && width !== void 0 && width.min ? Math.max(50, width.min) : 50,
    max: width !== null && width !== void 0 && width.max ? Math.min(700, width.max) : 700,
    step: (width === null || width === void 0 ? void 0 : width.step) >= 1 ? Math.min(200, width.step) : 20
  };
  var heightConstraints = {
    min: height !== null && height !== void 0 && height.min ? Math.max(400, height.min) : 400,
    max: height !== null && height !== void 0 && height.max ? Math.min(700, height.max) : 700,
    step: (height === null || height === void 0 ? void 0 : height.step) >= 1 ? Math.min(200, height.step) : 20
  };
  var gridOptions = gridValues && gridValues.range ? {
    customValues: gridValues.range
  } : {
    min: 0,
    max: 10000
  };
  var labelOptions = labelValues && labelValues.range ? {
    customValues: labelValues.range
  } : {
    min: 0,
    max: 10000
  };

  var stepConfig = /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.rowView
  }, /*#__PURE__*/_react["default"].createElement(_configUi.NumberTextFieldCustom, (0, _extends2["default"])({
    className: classes.mediumTextField,
    label: "Grid Interval",
    value: range.step,
    variant: "outlined",
    onChange: function onChange(e, v) {
      return onRangeChanged('step', v, e);
    }
  }, gridOptions)), /*#__PURE__*/_react["default"].createElement(_configUi.NumberTextFieldCustom, (0, _extends2["default"])({
    className: classes.mediumTextField,
    label: 'Label Interval',
    value: range.labelStep,
    variant: 'outlined',
    onChange: function onChange(e, v) {
      return onRangeChanged('labelStep', v, e);
    }
  }, labelOptions)));

  var handleAlertDialog = function handleAlertDialog(openStatus, callback) {
    setAlertDialog(function (prevState) {
      return _objectSpread(_objectSpread({}, prevState), {}, {
        open: openStatus
      });
    }, function () {
      if (callback) {
        callback();
      }
    });
    setOpen(openStatus);
  };

  var setPropertiesToFalse = function setPropertiesToFalse(data, property) {
    return data.map(function (obj) {
      if (obj.hasOwnProperty(property)) {
        obj[property] = property == 'interactive' ? true : false;
      }

      return obj;
    });
  };

  var removeOutOfRangeValues = function removeOutOfRangeValues(updateModel) {
    var correctAnswer = model.correctAnswer,
        data = model.data;

    if (changeInteractiveEnabled === false) {
      setPropertiesToFalse(data, 'interactive');
    }

    if (changeEditableEnabled === false) {
      setPropertiesToFalse(data, 'editable');
    }

    resetValues(data, updateModel, range, onChange, model);
    resetValues(correctAnswer.data, false, range, onChange, model);
  };

  var setCategoryDefaultLabel = function setCategoryDefaultLabel() {
    var studentCategoryDefaultLabel = studentNewCategoryDefaultLabel === null || studentNewCategoryDefaultLabel === void 0 ? void 0 : studentNewCategoryDefaultLabel.label;
    onChange(_objectSpread(_objectSpread({}, model), {}, {
      studentCategoryDefaultLabel: studentCategoryDefaultLabel
    }));
  };

  var rangeProps = function rangeProps(chartType) {
    return chartType.includes('Plot') ? {
      min: 3,
      max: 10
    } : {
      min: 0.05,
      max: 10000
    };
  };

  var onSizeChanged = function onSizeChanged(key, value) {
    var graph = _objectSpread(_objectSpread({}, size), {}, (0, _defineProperty2["default"])({}, key, value));

    onChange(_objectSpread(_objectSpread({}, model), {}, {
      graph: graph
    }));
  };

  var isOutOfRange = function isOutOfRange(data, range) {
    return (data || []).find(function (d) {
      return d.value > range.max || d.value - range.step * Math.floor(d.value / range.step) !== 0;
    });
  };

  var onRangeChanged = function onRangeChanged(key, value, e) {
    // use reset values to restore range to initial values
    setResetValue(range[key]);
    setRangeKey(key);
    range[key] = value;

    if (key === 'max' || key === 'step') {
      // check if current chart values are invalid for given range step/max
      var outOfRange = isOutOfRange(model.data, range) || isOutOfRange(model.correctAnswer.data, range);

      if (outOfRange && JSON.stringify(e) !== '{}') {
        setOpen(true);
      } else {
        onChange(_objectSpread(_objectSpread({}, model), {}, {
          range: range
        }));
      }
    } else {
      onChange(_objectSpread(_objectSpread({}, model), {}, {
        range: range
      }));
    }
  };

  (0, _react.useEffect)(function () {
    removeOutOfRangeValues(true);
    setCategoryDefaultLabel();
  }, []);
  (0, _react.useEffect)(function () {
    if (open) {
      setAlertDialog({
        open: true,
        title: 'Warning',
        text: 'This change will remove values defined for one or more categories',
        onConfirm: function onConfirm() {
          removeOutOfRangeValues();
          handleAlertDialog(false, onChange(_objectSpread(_objectSpread({}, model), {}, {
            range: range,
            correctAnswer: correctAnswer
          })));
        },
        onClose: function onClose() {
          range[rangeKey] = resetValue;
          handleAlertDialog(false);
        }
      });
    }
  }, [open]);
  var isValidPlot = range.step === 1 && range.labelStep === 1 && 3 <= range.max && range.max <= 10;

  var getPlotConfiguration = function getPlotConfiguration() {
    rangeProps.min = 3;
    rangeProps.max = 10;
    range.max = 10;
    range.step = 1;
    range.labelStep = 1;
    onChange(_objectSpread(_objectSpread({}, model), {}, {
      range: range
    }));
  };

  var onChartTypeChange = function onChartTypeChange(chartType) {
    if (chartType.includes('Plot')) {
      // The selected chart type does not support the current chart configuration
      if (!isValidPlot) {
        setAlertDialog({
          open: true,
          title: 'Warning',
          text: 'The selected chart type does not support the current chart configuration. Reset chart configuration?',
          onConfirm: function onConfirm() {
            getPlotConfiguration();
            removeOutOfRangeValues();
            handleAlertDialog(false, onChange(_objectSpread(_objectSpread({}, model), {}, {
              range: range,
              chartType: chartType
            })));
          },
          onClose: function onClose() {
            handleAlertDialog(false);
          }
        });
        return;
      }

      rangeProps.min = 3;
      rangeProps.max = 10;
      onChange(_objectSpread(_objectSpread({}, model), {}, {
        chartType: chartType
      }));
      return;
    }

    onChange(_objectSpread(_objectSpread({}, model), {}, {
      chartType: chartType
    }));
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.wrapper
  }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    variant: 'subtitle1'
  }, "Configure Chart"), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.content
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.rowView
  }, /*#__PURE__*/_react["default"].createElement(_chartType["default"], {
    value: model.chartType,
    onChange: function onChange(e) {
      return onChartTypeChange(e.target.value);
    },
    availableChartTypes: availableChartTypes,
    chartTypeLabel: chartTypeLabel
  }), /*#__PURE__*/_react["default"].createElement(_configUi.NumberTextFieldCustom, {
    className: classes.mediumTextField,
    label: "Max Value",
    value: range.max,
    min: rangeProps(model.chartType).min,
    max: rangeProps(model.chartType).max,
    variant: "outlined",
    onChange: function onChange(e, v) {
      return onRangeChanged('max', v, e);
    }
  })), !model.chartType.includes('Plot') && stepConfig, showInConfigPanel && /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.dimensions
  }, /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_Typography["default"], null, "Dimensions(px)")), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.columnView
  }, /*#__PURE__*/_react["default"].createElement(_configUi.NumberTextFieldCustom, {
    className: classes.textField,
    label: 'Width',
    value: size.width,
    min: widthConstraints.min,
    max: widthConstraints.max,
    step: widthConstraints.step,
    variant: 'outlined',
    onChange: function onChange(e, v) {
      return onSizeChanged('width', v);
    }
  }), /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    className: classes.disabled
  }, "Min 50, Max 700")), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.columnView
  }, /*#__PURE__*/_react["default"].createElement(_configUi.NumberTextFieldCustom, {
    className: classes.textField,
    label: 'Height',
    value: size.height,
    min: heightConstraints.min,
    max: heightConstraints.max,
    step: heightConstraints.step,
    variant: 'outlined',
    onChange: function onChange(e, v) {
      return onSizeChanged('height', v);
    }
  }), /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    className: classes.disabled
  }, "Min 400, Max 700")))), /*#__PURE__*/_react["default"].createElement(_configUi.AlertDialog, {
    open: alertDialog.open,
    title: alertDialog.title,
    text: alertDialog.text,
    onClose: alertDialog.onClose,
    onConfirm: alertDialog.onConfirm
  }));
};

ConfigureChartPanel.propTypes = {
  classes: _propTypes["default"].object,
  chartDimensions: _propTypes["default"].object,
  domain: _propTypes["default"].object,
  gridValues: _propTypes["default"].object,
  labelValues: _propTypes["default"].object,
  model: _propTypes["default"].object,
  onChange: _propTypes["default"].func,
  range: _propTypes["default"].object,
  chartDimension: _propTypes["default"].object,
  size: _propTypes["default"].object,
  studentNewCategoryDefaultLabel: _propTypes["default"].object,
  availableChartTypes: _propTypes["default"].object,
  chartTypeLabel: _propTypes["default"].string
};

var styles = function styles(theme) {
  return {
    wrapper: {
      width: '450px'
    },
    content: {
      display: 'flex',
      flexDirection: 'column',
      width: '100%',
      marginTop: theme.spacing.unit * 3
    },
    columnView: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center'
    },
    rowView: {
      display: 'flex',
      justifyContent: 'space-around',
      alignItems: 'center'
    },
    textField: {
      width: '130px',
      margin: "".concat(theme.spacing.unit, "px ").concat(theme.spacing.unit / 2, "px")
    },
    mediumTextField: {
      width: '160px',
      margin: "".concat(theme.spacing.unit, "px ").concat(theme.spacing.unit / 2, "px")
    },
    largeTextField: {
      width: '230px',
      margin: "".concat(theme.spacing.unit, "px ").concat(theme.spacing.unit / 2, "px")
    },
    text: {
      fontStyle: 'italic',
      margin: "".concat(theme.spacing.unit, "px 0")
    },
    dimensions: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      margin: "".concat(theme.spacing.unit * 3, "px 0")
    },
    disabled: {
      color: _renderUi.color.disabled()
    }
  };
};

var _default = (0, _styles.withStyles)(styles)(ConfigureChartPanel);

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