import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _createForOfIteratorHelper from "@babel/runtime/helpers/createForOfIteratorHelper";
var _excluded = ["formData", "schema", "uiSchema"];
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import { TableFooter } from "@mui/material";
import { format } from 'date-fns';
import Field from '../Field';
import { dynamicElements } from '../../useDynamicElements';
import { calcTypeSign } from "../../configToSchemas/types/calcTable.js";
import { jsx as _jsx } from "react/jsx-runtime";
import { createElement as _createElement } from "react";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
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 = _createForOfIteratorHelper(formData),
        _step;

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

        if (isAnswered(_objectSpread(_objectSpread({}, 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 = _createForOfIteratorHelper(formData.table),
              _step2;

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

              var _iterator3 = _createForOfIteratorHelper(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 = _createForOfIteratorHelper(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;
    }
  }
};

export default (function (props) {
  var _uiSchema$uiOptions, _uiSchema$uiOptions2, _schema$properties;

  var formData = props.formData,
      schema = props.schema,
      uiSchema = props.uiSchema,
      otherProps = _objectWithoutProperties(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 && 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 && 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 && format(new Date(formData.start), 'd.M.yyyy');
      end = formData.end && 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__*/_jsx(Field, _objectSpread(_objectSpread({}, 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__*/_jsx(Field, _objectSpread(_objectSpread({}, 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 = dynamicElements(_objectSpread(_objectSpread({}, 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__*/_createElement(Field, _objectSpread(_objectSpread({}, 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__*/_createElement(Field, _objectSpread(_objectSpread({}, 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__*/_createElement(Field, _objectSpread(_objectSpread({}, 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 + calcTypeSign[column.calcType];
    }) : element.tableColumns;
    var rows = element.useRowTitles ? element.rowTitles : [];
    return /*#__PURE__*/_jsx(TableContainer, {
      children: /*#__PURE__*/_jsxs(Table, {
        size: "small",
        children: [/*#__PURE__*/_jsx(TableHead, {
          children: /*#__PURE__*/_jsxs(TableRow, {
            children: [element.useRowTitles ? /*#__PURE__*/_jsx(TableCell, {}, "header-row") : /*#__PURE__*/_jsx(_Fragment, {}), columns.map(function (item, index) {
              return /*#__PURE__*/_jsx(TableCell, {
                children: item
              }, 'header-' + index);
            })]
          })
        }), /*#__PURE__*/_jsx(TableBody, {
          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__*/_jsxs(TableRow, {
              children: [element.useRowTitles ? /*#__PURE__*/_jsx(TableCell, {
                style: {
                  fontWeight: 'bold'
                },
                children: rowIndex < rows.length ? rows[rowIndex] : ''
              }, 'row-title-' + rowIndex) : /*#__PURE__*/_jsx(_Fragment, {}), rowItem.map(function (item, itemIndex) {
                return /*#__PURE__*/_jsx(TableCell, {
                  children: item
                }, 'cell-' + rowIndex + '-' + itemIndex);
              })]
            }, 'row-' + rowIndex);
          })
        }), element.type === 'calcTable' && /*#__PURE__*/_jsxs(TableFooter, {
          children: [element.useRowTitles && /*#__PURE__*/_jsx(TableCell, {}), formData.resultRow && formData.resultRow.length > 0 && formData.resultRow.map(function (result) {
            return /*#__PURE__*/_jsx(TableCell, {
              style: {
                fontWeight: 'bold'
              },
              children: result !== '' ? "= ".concat(result) : ''
            });
          })]
        })]
      })
    });
  }
});
//# sourceMappingURL=object.js.map