"use strict";

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

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

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

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

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

var _Table = _interopRequireDefault(require("@material-ui/core/Table"));

var _TableBody = _interopRequireDefault(require("@material-ui/core/TableBody"));

var _TableCell = _interopRequireDefault(require("@material-ui/core/TableCell"));

var _TableContainer = _interopRequireDefault(require("@material-ui/core/TableContainer"));

var _TableHead = _interopRequireDefault(require("@material-ui/core/TableHead"));

var _TableRow = _interopRequireDefault(require("@material-ui/core/TableRow"));

var _material = require("@mui/material");

var _dateFns = require("date-fns");

var _Field = _interopRequireDefault(require("../Field"));

var _useDynamicElements = require("../../useDynamicElements");

var _calcTable = require("../../configToSchemas/types/calcTable.cjs");

var _jsxRuntime = require("react/jsx-runtime");

var _react = require("react");

var _excluded = ["formData", "schema", "uiSchema"];
var STATIC_ELEMENTS = ['body', 'image', 'title', 'pageTitle', 'subtitle', 'review'];

var isAnswered = function isAnswered(element, formData) {
  if (STATIC_ELEMENTS.includes(element === null || element === void 0 ? void 0 : element.type)) {
    // Static elements like body, title etc
    return true;
  } else if (formData === undefined || formData === '' || formData.length === 0) {
    // Formdata is empty
    return false;
  } else if (element === null || element === void 0 ? void 0 : element.list) {
    // Check every item in a list. If even one exists, return true
    var _iterator = (0, _createForOfIteratorHelper2["default"])(formData),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var formDatum = _step.value;

        if (isAnswered((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, element), {}, {
          list: false
        }), formDatum)) {
          return true;
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return false;
  } else {
    // check rest of the situations based on element.type
    switch (element === null || element === void 0 ? void 0 : element.type) {
      case 'dateRange':
        return formData.start || formData.end;

      case 'boolean':
        if (formData) {
          return true;
        } else {
          return element.widget !== 'checkbox';
        }

      case 'confirmField':
        return formData.value !== undefined && formData.value !== '' && formData.confirmation !== undefined && formData.confirmation !== '';

      case 'calcTable':
      case 'tableField':
        if (formData.table.length === 0) {
          return false;
        } else {
          var _iterator2 = (0, _createForOfIteratorHelper2["default"])(formData.table),
              _step2;

          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var row = _step2.value;

              var _iterator3 = (0, _createForOfIteratorHelper2["default"])(row),
                  _step3;

              try {
                for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
                  var column = _step3.value;

                  if (column && column !== '') {
                    return true;
                  }
                }
              } catch (err) {
                _iterator3.e(err);
              } finally {
                _iterator3.f();
              }
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }

          return false;
        }

      case 'formGroup':
        var _iterator4 = (0, _createForOfIteratorHelper2["default"])(element.elements),
            _step4;

        try {
          for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
            var subElement = _step4.value;

            if (isAnswered(subElement, formData[subElement.key])) {
              return true;
            }
          }
        } catch (err) {
          _iterator4.e(err);
        } finally {
          _iterator4.f();
        }

        return false;

      default:
        return true;
    }
  }
};

var _default = function _default(props) {
  var _uiSchema$uiOptions, _uiSchema$uiOptions2, _schema$properties;

  var formData = props.formData,
      schema = props.schema,
      uiSchema = props.uiSchema,
      otherProps = (0, _objectWithoutProperties2["default"])(props, _excluded); // dateRange

  if (((_uiSchema$uiOptions = uiSchema['ui:options']) === null || _uiSchema$uiOptions === void 0 ? void 0 : _uiSchema$uiOptions.element.type) === 'dateRange') {
    var _start, _end;

    var start;
    var end;

    try {
      var _otherProps$reviewPro, _otherProps$reviewPro2, _otherProps$reviewPro3, _otherProps$reviewPro4;

      start = formData.start && (0, _dateFns.format)(new Date(formData.start), (_otherProps$reviewPro = otherProps === null || otherProps === void 0 ? void 0 : (_otherProps$reviewPro2 = otherProps.reviewProps) === null || _otherProps$reviewPro2 === void 0 ? void 0 : _otherProps$reviewPro2.dateFormat) !== null && _otherProps$reviewPro !== void 0 ? _otherProps$reviewPro : 'd.M.yyyy');
      end = formData.end && (0, _dateFns.format)(new Date(formData.end), (_otherProps$reviewPro3 = otherProps === null || otherProps === void 0 ? void 0 : (_otherProps$reviewPro4 = otherProps.reviewProps) === null || _otherProps$reviewPro4 === void 0 ? void 0 : _otherProps$reviewPro4.dateFormat) !== null && _otherProps$reviewPro3 !== void 0 ? _otherProps$reviewPro3 : 'd.M.yyyy');
    } catch (e) {
      var _otherProps$reviewPro5;

      // eslint-disable-next-line no-console
      console.warn("".concat(otherProps === null || otherProps === void 0 ? void 0 : (_otherProps$reviewPro5 = otherProps.reviewProps) === null || _otherProps$reviewPro5 === void 0 ? void 0 : _otherProps$reviewPro5.dateFormat, " is not a valid dateformat, using default format d.M.yyyy"));
      start = formData.start && (0, _dateFns.format)(new Date(formData.start), 'd.M.yyyy');
      end = formData.end && (0, _dateFns.format)(new Date(formData.end), 'd.M.yyyy');
    }

    var dateValue = "".concat((_start = start) !== null && _start !== void 0 ? _start : '', " - ").concat((_end = end) !== null && _end !== void 0 ? _end : '');
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Field["default"], (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
      formData: dateValue,
      schema: {
        schema: schema,
        type: 'string'
      },
      uiSchema: uiSchema
    }));
  } // confirmField


  if (((_uiSchema$uiOptions2 = uiSchema['ui:options']) === null || _uiSchema$uiOptions2 === void 0 ? void 0 : _uiSchema$uiOptions2.element.type) === 'confirmField') {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Field["default"], (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
      formData: formData.value,
      schema: {
        schema: schema,
        type: 'string'
      },
      uiSchema: uiSchema
    }));
  } // forms and formGroups


  if (uiSchema['ui:order']) {
    var _uiSchema$uiOptions3, _uiSchema$uiOptions3$;

    if (((_uiSchema$uiOptions3 = uiSchema['ui:options']) === null || _uiSchema$uiOptions3 === void 0 ? void 0 : (_uiSchema$uiOptions3$ = _uiSchema$uiOptions3.element) === null || _uiSchema$uiOptions3$ === void 0 ? void 0 : _uiSchema$uiOptions3$.type) === 'formGroup') {
      var elementKeys = (0, _useDynamicElements.dynamicElements)((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, uiSchema['ui:options'].element), {}, {
        list: false,
        title: undefined
      }), props.formData).elements.map(function (element) {
        return element.key;
      });
      return uiSchema['ui:order'].filter(function (name) {
        return elementKeys.includes(name);
      }).filter(function (key) {
        var _uiSchema$key$uiOpti, _uiSchema$key, _uiSchema$key$uiOpti2, _uiSchema$key$uiOpti3, _uiSchema$key2, _uiSchema$key2$uiOpt;

        return props.hideNotAnswered ? isAnswered((_uiSchema$key$uiOpti = (_uiSchema$key = uiSchema[key]) === null || _uiSchema$key === void 0 ? void 0 : (_uiSchema$key$uiOpti2 = _uiSchema$key['ui:options']) === null || _uiSchema$key$uiOpti2 === void 0 ? void 0 : (_uiSchema$key$uiOpti3 = _uiSchema$key$uiOpti2.items) === null || _uiSchema$key$uiOpti3 === void 0 ? void 0 : _uiSchema$key$uiOpti3.element) !== null && _uiSchema$key$uiOpti !== void 0 ? _uiSchema$key$uiOpti : (_uiSchema$key2 = uiSchema[key]) === null || _uiSchema$key2 === void 0 ? void 0 : (_uiSchema$key2$uiOpt = _uiSchema$key2['ui:options']) === null || _uiSchema$key2$uiOpt === void 0 ? void 0 : _uiSchema$key2$uiOpt.element, formData[key]) : true;
      }).map(function (name) {
        return /*#__PURE__*/(0, _react.createElement)(_Field["default"], (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
          key: name,
          formData: formData === null || formData === void 0 ? void 0 : formData[name],
          schema: schema.properties[name],
          uiSchema: uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema[name]
        }));
      });
    } else {
      if (props.hideNotAnswered) {
        return uiSchema['ui:order'].filter(function (key) {
          return isAnswered(props.config.elements.find(function (el) {
            return el.key === key;
          }), formData[key]);
        }).map(function (name) {
          return /*#__PURE__*/(0, _react.createElement)(_Field["default"], (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
            key: name,
            formData: formData === null || formData === void 0 ? void 0 : formData[name],
            schema: schema.properties[name],
            uiSchema: uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema[name]
          }));
        });
        /*
        // Remove empty pages. Remove comments from lines 121-133 and 159 to use
        const hiddenRemovedKeys = uiSchema['ui:order']
          .filter(key => isAnswered(props.config.elements.find(el => el.key === key), formData[key]));
        const noEmptyPages = [];
        // eslint-disable-next-line @super-template/no-loops/no-loops
        for (const i in hiddenRemovedKeys) {
          if (Number(i) < hiddenRemovedKeys.length - 1) {
            const currentElement = props.config.elements.find(el => el.key === hiddenRemovedKeys[i]);
            const nextElement = props.config.elements.find(el => el.key === hiddenRemovedKeys[Number(i) + 1]);
            if (!(currentElement.type === 'pageTitle' && nextElement.type === 'pageTitle')) {
              noEmptyPages.push(hiddenRemovedKeys[i])
            }
          } else if (props.config.elements.find(el => el.key === hiddenRemovedKeys[i]).type !== 'pageTitle') {
            noEmptyPages.push(hiddenRemovedKeys[i])
          }
        }
        return noEmptyPages.map((name) => (
            <Field
              {...otherProps}
              key={name}
              formData={formData?.[name]}
              schema={schema.properties[name]}
              uiSchema={uiSchema?.[name]}
            />
          ));
          */
      } else {
        return uiSchema['ui:order'].map(function (name) {
          return /*#__PURE__*/(0, _react.createElement)(_Field["default"], (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
            key: name,
            formData: formData === null || formData === void 0 ? void 0 : formData[name],
            schema: schema.properties[name],
            uiSchema: uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema[name]
          }));
        });
      }
    }
  } // tables


  if ((_schema$properties = schema.properties) === null || _schema$properties === void 0 ? void 0 : _schema$properties.table) {
    var _formData$table;

    var element = uiSchema['ui:options'].element;
    var columns = element.type === 'calcTable' ? element.calcTableColumns.map(function (column) {
      return column.name + _calcTable.calcTypeSign[column.calcType];
    }) : element.tableColumns;
    var rows = element.useRowTitles ? element.rowTitles : [];
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableContainer["default"], {
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Table["default"], {
        size: "small",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_TableHead["default"], {
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_TableRow["default"], {
            children: [element.useRowTitles ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {}, "header-row") : /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {}), columns.map(function (item, index) {
              return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
                children: item
              }, 'header-' + index);
            })]
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableBody["default"], {
          children: formData === null || formData === void 0 ? void 0 : (_formData$table = formData.table) === null || _formData$table === void 0 ? void 0 : _formData$table.map(function (rowItem, rowIndex) {
            return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_TableRow["default"], {
              children: [element.useRowTitles ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
                style: {
                  fontWeight: 'bold'
                },
                children: rowIndex < rows.length ? rows[rowIndex] : ''
              }, 'row-title-' + rowIndex) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {}), rowItem.map(function (item, itemIndex) {
                return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
                  children: item
                }, 'cell-' + rowIndex + '-' + itemIndex);
              })]
            }, 'row-' + rowIndex);
          })
        }), element.type === 'calcTable' && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_material.TableFooter, {
          children: [element.useRowTitles && /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {}), formData.resultRow && formData.resultRow.length > 0 && formData.resultRow.map(function (result) {
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
              style: {
                fontWeight: 'bold'
              },
              children: result !== '' ? "= ".concat(result) : ''
            });
          })]
        })]
      })
    });
  }
};

exports["default"] = _default;
//# sourceMappingURL=object.cjs.map