"use strict";

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

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

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

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 _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

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

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 _get2 = _interopRequireDefault(require("lodash/get"));

var _set = _interopRequireDefault(require("lodash/set"));

var _Select = _interopRequireDefault(require("@material-ui/core/Select"));

var _Input = _interopRequireDefault(require("@material-ui/core/Input"));

var _MenuItem = _interopRequireDefault(require("@material-ui/core/MenuItem"));

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

var _toggle = _interopRequireDefault(require("./toggle"));

var _twoChoice = require("../two-choice");

var _settingsRadioLabel = _interopRequireDefault(require("./settings-radio-label"));

var _numberTextField = _interopRequireDefault(require("../number-text-field"));

var _checkbox = _interopRequireDefault(require("../checkbox"));

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

var _excluded = ["isConfigProperty"];

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

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 log = (0, _debug["default"])('pie-lib:config-ui:settings:panel');
var labelValue = {
  label: _propTypes["default"].string,
  value: _propTypes["default"].string
};
var baseTypes = {
  label: _propTypes["default"].string,
  value: _propTypes["default"].string,
  onChange: _propTypes["default"].func
};

var CheckboxChoice = function CheckboxChoice(_ref) {
  var label = _ref.label,
      value = _ref.value,
      _onChange = _ref.onChange;
  return /*#__PURE__*/_react["default"].createElement(_checkbox["default"], {
    checked: value,
    label: label,
    onChange: function onChange(event) {
      _onChange(event.target.checked);
    }
  });
};

CheckboxChoice.propTypes = {
  label: _propTypes["default"].string,
  value: _propTypes["default"].bool,
  onChange: _propTypes["default"].func
};

var Radio = function Radio(_ref2) {
  var classes = _ref2.classes,
      label = _ref2.label,
      value = _ref2.value,
      onChange = _ref2.onChange,
      choices = _ref2.choices;
  return /*#__PURE__*/_react["default"].createElement(_twoChoice.NChoice, {
    className: classes.radioSettings,
    direction: "horizontal",
    customLabel: _settingsRadioLabel["default"],
    value: value,
    header: label,
    opts: choices,
    onChange: onChange
  });
};

Radio.propTypes = _objectSpread(_objectSpread({}, baseTypes), {}, {
  choices: _propTypes["default"].arrayOf(_propTypes["default"].shape(labelValue))
});
var StyledRadio = (0, _styles.withStyles)(function (theme) {
  return {
    radioSettings: {
      marginTop: theme.spacing.unit / 2,
      paddingBottom: theme.spacing.unit / 2,
      width: '100%',
      '& > label': {
        color: 'rgba(0, 0, 0, 0.89)',
        transform: 'translate(0, 10px) scale(1)',
        fontSize: '14px'
      },
      '& > div': {
        marginTop: theme.spacing.unit * 2.5
      }
    },
    label: {
      display: 'none'
    }
  };
})(Radio);
var Dropdown = (0, _styles.withStyles)(function (theme) {
  return {
    label: {
      margin: 0,
      fontSize: theme.typography.fontSize
    },
    wrapper: {
      marginTop: theme.spacing.unit / 2,
      border: '2px solid lightgrey',
      borderRadius: '4px',
      padding: "0 ".concat(theme.spacing.unit, "px")
    }
  };
})(function (_ref3) {
  var classes = _ref3.classes,
      label = _ref3.label,
      value = _ref3.value,
      _onChange2 = _ref3.onChange,
      _ref3$choices = _ref3.choices,
      choices = _ref3$choices === void 0 ? [] : _ref3$choices;

  var getItemLabel = function getItemLabel(l) {
    return typeof l === 'string' ? l : l.label;
  };

  var getItemValue = function getItemValue(l) {
    return typeof l === 'string' ? l : l.value;
  };

  return /*#__PURE__*/_react["default"].createElement("div", null, label && /*#__PURE__*/_react["default"].createElement("p", {
    className: classes.label
  }, label), /*#__PURE__*/_react["default"].createElement(_Select["default"], {
    className: classes.wrapper,
    value: value || choices && choices[0],
    onChange: function onChange(_ref4) {
      var target = _ref4.target;
      return _onChange2(target.value);
    },
    input: /*#__PURE__*/_react["default"].createElement(_Input["default"], {
      id: "dropdown-".concat(label)
    }),
    disableUnderline: true
  }, choices.map(function (l, index) {
    return /*#__PURE__*/_react["default"].createElement(_MenuItem["default"], {
      key: index,
      value: getItemValue(l)
    }, getItemLabel(l));
  })));
});
Dropdown.propTypes = _objectSpread(_objectSpread({}, baseTypes), {}, {
  choices: _propTypes["default"].arrayOf(_propTypes["default"].string)
});
var TextField = (0, _styles.withStyles)(function (theme) {
  return {
    field: {
      marginRight: theme.spacing.unit * 3,
      marginTop: theme.spacing.unit
    }
  };
})(function (_ref5) {
  var classes = _ref5.classes,
      label = _ref5.label;
  return /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    className: classes.field
  }, label);
});
var NumberField = (0, _styles.withStyles)(function (theme) {
  return {
    field: {
      width: '35%',
      marginRight: theme.spacing.unit * 3,
      marginTop: theme.spacing.unit
    },
    wrapper: {
      marginTop: theme.spacing.unit / 2,
      border: '2px solid lightgrey',
      borderRadius: '4px',
      padding: "0 ".concat(theme.spacing.unit, "px")
    }
  };
})(function (_ref6) {
  var classes = _ref6.classes,
      label = _ref6.label,
      value = _ref6.value,
      _ref6$onChange = _ref6.onChange,
      _onChange3 = _ref6$onChange === void 0 ? function () {} : _ref6$onChange,
      suffix = _ref6.suffix,
      min = _ref6.min,
      max = _ref6.max;

  return /*#__PURE__*/_react["default"].createElement(_numberTextField["default"], {
    label: label || 'Label',
    value: value,
    max: max,
    min: min,
    onChange: function onChange(ev, value) {
      return _onChange3(value);
    },
    suffix: suffix,
    className: classes.field,
    showErrorWhenOutsideRange: true,
    inputClassName: classes.wrapper,
    disableUnderline: true,
    classes: classes
  });
});
NumberField.propTypes = _objectSpread(_objectSpread({}, baseTypes), {}, {
  classes: _propTypes["default"].object,
  suffix: _propTypes["default"].string,
  min: _propTypes["default"].number,
  max: _propTypes["default"].number,
  value: _propTypes["default"].number
});
TextField.propTypes = _objectSpread({}, baseTypes);

var ToggleWrapper = function ToggleWrapper(_ref7) {
  var disabled = _ref7.disabled,
      label = _ref7.label,
      value = _ref7.value,
      onChange = _ref7.onChange;
  return /*#__PURE__*/_react["default"].createElement(_toggle["default"], {
    label: label,
    checked: !!value,
    disabled: !!disabled,
    toggle: onChange
  });
};

ToggleWrapper.propTypes = _objectSpread(_objectSpread({}, baseTypes), {}, {
  value: _propTypes["default"].bool
});
var tagMap = {
  toggle: ToggleWrapper,
  radio: StyledRadio,
  dropdown: Dropdown,
  numberField: NumberField,
  checkbox: CheckboxChoice,
  textField: TextField
};
var Group = (0, _styles.withStyles)(function (theme) {
  return {
    group: {
      margin: "0 0 ".concat(theme.spacing.unit * 2, "px 0")
    },
    groupHeader: {
      color: '#495B8F',
      fontSize: theme.typography.fontSize + 2,
      fontWeight: 600,
      marginBottom: theme.spacing.unit
    },
    numberFields: {
      fontSize: theme.typography.fontSize,
      marginBottom: 0
    }
  };
})(function (props) {
  var classes = props.classes,
      model = props.model,
      label = props.label,
      group = props.group,
      configuration = props.configuration,
      _onChange4 = props.onChange;
  /**
   * @param group - the group of settings
   * @param key - the key(or path) to be used to set or get from model or configuration
   * @param innerKey - the key(or path) to be used to get from the group (used only for numberField type)
   * @returns tag that corresponds to element type */

  var getTag = function getTag(group, key, innerKey) {
    var _get = (0, _get2["default"])(group, innerKey || key),
        isConfigProperty = _get.isConfigProperty,
        properties = (0, _objectWithoutProperties2["default"])(_get, _excluded);

    var value = isConfigProperty ? (0, _get2["default"])(configuration, key) : (0, _get2["default"])(model, key);

    var tagProps = _objectSpread(_objectSpread({}, properties), {}, {
      key: key,
      value: value
    });

    var Tag = tagMap[tagProps.type];
    return /*#__PURE__*/_react["default"].createElement(Tag, (0, _extends2["default"])({
      key: key
    }, tagProps, {
      onChange: function onChange(v) {
        return _onChange4(key, v, isConfigProperty);
      }
    }));
  };

  var content = function content(group, key) {
    var currentGroup = group[key];

    if (!currentGroup) {
      return null;
    }

    var type = currentGroup.type,
        label = currentGroup.label,
        fields = currentGroup.fields,
        choices = currentGroup.choices;

    if (type === 'numberFields') {
      return /*#__PURE__*/_react["default"].createElement("div", {
        key: "numberField-".concat(label)
      }, /*#__PURE__*/_react["default"].createElement("p", {
        className: classes.numberFields
      }, label), Object.keys(fields).map(function (fieldKey) {
        return getTag(group, "".concat(key, ".").concat(fieldKey), "".concat(key, ".fields.").concat(fieldKey));
      }));
    }

    if (type === 'checkboxes') {
      return /*#__PURE__*/_react["default"].createElement("div", {
        key: "checkbox-".concat(label)
      }, /*#__PURE__*/_react["default"].createElement("p", null, label), Object.keys(choices).map(function (choiceKey) {
        return getTag(group, "".concat(key, ".").concat(choiceKey), "".concat(key, ".choices.").concat(choiceKey));
      }));
    } // if type is toggle, radio, dropdown, numberField or numberText


    return getTag(group, key);
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.group
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.groupHeader
  }, label), Object.keys(group).map(function (key) {
    return content(group, key);
  }));
});

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

  var _super = _createSuper(Panel);

  function Panel() {
    var _this;

    (0, _classCallCheck2["default"])(this, Panel);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "change", function (key, value) {
      var isConfigProperty = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      log('[changeModel]', key, value);
      var _this$props = _this.props,
          onChangeModel = _this$props.onChangeModel,
          onChangeConfiguration = _this$props.onChangeConfiguration;

      var model = _objectSpread({}, _this.props.model);

      var configuration = _objectSpread({}, _this.props.configuration);

      if (isConfigProperty) {
        (0, _set["default"])(configuration, key, value);
        onChangeConfiguration(configuration, key);
      } else {
        (0, _set["default"])(model, key, value);
        onChangeModel(model, key);
      }
    });
    return _this;
  }

  (0, _createClass2["default"])(Panel, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props2 = this.props,
          groups = _this$props2.groups,
          model = _this$props2.model,
          configuration = _this$props2.configuration,
          modal = _this$props2.modal;
      log('render:', model);
      var renderedGroups = Object.keys(groups || {}).map(function (group) {
        var showGroup = Object.entries(groups[group]).some(function (_ref8) {
          var _ref9 = (0, _slicedToArray2["default"])(_ref8, 2),
              propVal = _ref9[1];

          return !!propVal;
        });

        if (showGroup) {
          return /*#__PURE__*/_react["default"].createElement(Group, {
            label: group,
            key: group,
            model: model,
            configuration: configuration,
            group: groups[group],
            onChange: _this2.change
          });
        }

        return null;
      });
      return /*#__PURE__*/_react["default"].createElement("div", null, renderedGroups, modal);
    }
  }]);
  return Panel;
}(_react["default"].Component);

exports.Panel = Panel;
(0, _defineProperty2["default"])(Panel, "propTypes", {
  model: _propTypes["default"].object,
  configuration: _propTypes["default"].object,
  groups: _propTypes["default"].object,
  onChangeModel: _propTypes["default"].func,
  onChangeConfiguration: _propTypes["default"].func,
  modal: _propTypes["default"].object
});
(0, _defineProperty2["default"])(Panel, "defaultProps", {
  onChangeModel: function onChangeModel() {},
  onChangeConfiguration: function onChangeConfiguration() {}
});
var _default = Panel;
exports["default"] = _default;
//# sourceMappingURL=panel.js.map