/* eslint-disable no-param-reassign */
import React from "react";
import { connect } from "react-redux";
import produce from "immer";
import PropTypes from "prop-types";
import ModuleLoader from "../../ModuleLoader";
import { actions } from "../../../utils/redux";

var reducer = function reducer(state, action) {
  return produce(state || {
    hasError: false,
    code: false
  }, function (possibleState) {
    switch (action.type) {
      case actions.LAUNCH_ERROR:
        {
          possibleState.code = action.payload.code;
          possibleState.hasError = action.payload.hasError;
          break;
        }

      default:
        {// Do nothing
        }
    }
  });
};

var Handler = function Handler(_ref) {
  var children = _ref.children,
      pageErrors = _ref.pageErrors,
      hasError = _ref.hasError,
      code = _ref.code;

  if (hasError) {
    if (!pageErrors || !pageErrors[code]) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, children);
    }

    var PageError = pageErrors[code];
    return /*#__PURE__*/React.createElement(PageError, null, children);
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, children);
};

export var moduleConfig = {
  id: "errorHandler",
  reducerMap: {
    errorHandler: reducer
  },
  initialActions: [],
  finalActions: []
};
Handler.propTypes = {
  pageErrors: PropTypes.instanceOf(Object)
};
Handler.defaultProps = {
  pageErrors: {}
};

var mapStateToProps = function mapStateToProps(_ref2) {
  var errorHandler = _ref2.errorHandler;
  return {
    code: errorHandler ? errorHandler.code : false,
    hasError: errorHandler ? errorHandler.hasError : false
  };
};

export default (function (props) {
  return /*#__PURE__*/React.createElement(ModuleLoader, {
    Component: connect(mapStateToProps)(Handler),
    config: moduleConfig,
    componentProps: props
  });
});