"use strict";

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

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

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

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

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

var _reactIntl = require("react-intl");

var _lodash = require("lodash");

var _react = require("react");

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 _TextField = _interopRequireDefault(require("@material-ui/core/TextField"));

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

var _Delete = _interopRequireDefault(require("@material-ui/icons/Delete"));

var _Add = _interopRequireDefault(require("@material-ui/icons/Add"));

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

var _intl = require("@formatjs/intl");

var _rjsfCore = require("@visma/rjsf-core");

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

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

var useStyles = (0, _styles.makeStyles)({
  inputLabelRoot: {
    clip: "rect(0 0 0 0)",
    clipPath: "inset(50%)",
    height: 1,
    overflow: "hidden",
    position: "absolute",
    whiteSpace: "nowrap",
    width: 1
  },
  inputFormControl: {
    "label + &": {
      marginTop: 0
    }
  }
});
var tableLabel = (0, _reactIntl.defineMessage)({
  id: "Od6CNk",
  defaultMessage: [{
    "type": 1,
    "value": "tableName"
  }, {
    "type": 0,
    "value": " sarake "
  }, {
    "type": 1,
    "value": "columnName"
  }, {
    "type": 0,
    "value": " rivi "
  }, {
    "type": 1,
    "value": "row"
  }]
});
var defaultValue = '';

var makeTable = function makeTable(initValues, rows, cols) {
  return (0, _toConsumableArray2["default"])(Array(rows)).map(function (_, rowNum) {
    return (0, _toConsumableArray2["default"])(Array(cols)).map(function (_, colNum) {
      return initValues[rowNum] && initValues[rowNum][colNum] || defaultValue;
    });
  });
};

var getTotalRows = function getTotalRows(_ref) {
  var _uiSchema$uiOptions, _formData$table;

  var formData = _ref.formData,
      uiSchema = _ref.uiSchema;
  var field = ((_uiSchema$uiOptions = uiSchema['ui:options']) === null || _uiSchema$uiOptions === void 0 ? void 0 : _uiSchema$uiOptions.element) || {};
  var _field$tableRowMinimu = field.tableRowMinimum,
      tableRowMinimum = _field$tableRowMinimu === void 0 ? 0 : _field$tableRowMinimu;
  return Math.max(Number(tableRowMinimum), (formData === null || formData === void 0 ? void 0 : (_formData$table = formData.table) === null || _formData$table === void 0 ? void 0 : _formData$table.length) || 0);
};

var getTotalColumns = function getTotalColumns(_ref2) {
  var uiSchema = _ref2.uiSchema;
  var field = uiSchema['ui:options'].element || {};
  var _field$tableColumns = field.tableColumns,
      tableColumns = _field$tableColumns === void 0 ? [] : _field$tableColumns;
  return tableColumns.length || 0;
};

function TableField(props) {
  var disabled = props.disabled,
      readonly = props.readonly,
      onChange = props.onChange,
      formData = props.formData,
      errorSchema = props.errorSchema,
      uiSchema = props.uiSchema,
      idSchema = props.idSchema,
      schema = props.schema,
      rawErrors = props.rawErrors;
  var config = uiSchema['ui:options'].element;
  var _config$tableAddAllow = config.tableAddAllowed,
      tableAddAllowed = _config$tableAddAllow === void 0 ? false : _config$tableAddAllow,
      _config$tableRowMinim = config.tableRowMinimum,
      tableRowMinimum = _config$tableRowMinim === void 0 ? 0 : _config$tableRowMinim,
      _config$tableRowMaxim = config.tableRowMaximum,
      tableRowMaximum = _config$tableRowMaxim === void 0 ? Number.MAX_SAFE_INTEGER : _config$tableRowMaxim,
      _config$useLabel = config.useLabel,
      useLabel = _config$useLabel === void 0 ? false : _config$useLabel,
      _config$tableColumns = config.tableColumns,
      tableColumns = _config$tableColumns === void 0 ? [] : _config$tableColumns,
      _config$rowTitles = config.rowTitles,
      rowTitles = _config$rowTitles === void 0 ? [] : _config$rowTitles,
      _config$useRowTitles = config.useRowTitles,
      useRowTitles = _config$useRowTitles === void 0 ? false : _config$useRowTitles,
      label = config.label,
      title = config.title,
      description = config.description,
      id = config.id;
  var totalRows = getTotalRows(props);
  var totalCols = getTotalColumns(props);
  var intl = (0, _reactIntl.useIntl)();

  var _useState = (0, _react.useState)((0, _lodash.uniqueId)()),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      rev = _useState2[0],
      setRev = _useState2[1];

  var classes = useStyles();

  var ariaDescribedby = _rjsfCore.utils.ariaDescribedBy(idSchema.$id, uiSchema, rawErrors);

  var onPropertyChange = function onPropertyChange(tableData) {
    onChange({
      table: tableData
    }, errorSchema);

    if (totalRows !== tableData.length) {
      setRev((0, _lodash.uniqueId)());
    }
  };

  var onAddRow = function onAddRow(_) {
    onPropertyChange(makeTable(tableData, totalRows + 1, totalCols));
  };

  var onRemoveRow = function onRemoveRow(rowNum) {
    onPropertyChange(tableData.filter(function (_, index) {
      return index !== rowNum;
    }));
  };

  var tableData = makeTable((formData === null || formData === void 0 ? void 0 : formData.table) || [], totalRows, totalCols);

  var tableHeaders = function tableHeaders(ignoreTitleColumn) {
    var headers = tableColumns.map(function (columnName, index) {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
        children: columnName
      }, index);
    });

    if (useRowTitles && !ignoreTitleColumn) {
      headers.unshift( /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
        children: ""
      }, -1));
    }

    return headers;
  };

  var tableCells = tableData.map(function (row, rowNum) {
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_TableRow["default"], {
      children: [useRowTitles && /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
        style: {
          fontWeight: 'bold'
        },
        children: rowNum < rowTitles.length ? rowTitles[rowNum] : ''
      }), row.map(function (_, colNum) {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_TextField["default"], {
            id: "".concat(id, "-").concat(rowNum, "-").concat(colNum),
            style: {
              width: '100%'
            },
            variant: "outlined",
            size: "small",
            "aria-label": intl.formatMessage(tableLabel, {
              tableName: useLabel ? label : title,
              columnName: tableColumns[colNum],
              row: rowNum + 1
            }),
            label: useLabel ? label : title,
            defaultValue: tableData[rowNum][colNum],
            disabled: disabled,
            readOnly: readonly,
            onChange: function onChange(event) {
              tableData[rowNum][colNum] = event.target.value || defaultValue;
              onPropertyChange(tableData);
            },
            InputProps: {
              classes: {
                formControl: classes.inputFormControl
              },
              'aria-describedby': ariaDescribedby
            },
            InputLabelProps: {
              htmlFor: "".concat(id, "-").concat(rowNum, "-").concat(colNum),
              shrink: false,
              className: classes.inputLabelRoot
            }
          })
        }, "col-".concat(colNum));
      }).concat(tableData.length > tableRowMinimum ? rowNum >= tableRowMinimum ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_IconButton["default"], {
          "aria-label": intl.formatMessage({
            id: "7A0Mm1",
            defaultMessage: [{
              "type": 0,
              "value": "Poista rivi"
            }]
          }),
          onClick: function onClick(_) {
            onRemoveRow(rowNum);
          },
          disabled: disabled || readonly,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Delete["default"], {
            alt: intl.formatMessage({
              id: "7A0Mm1",
              defaultMessage: [{
                "type": 0,
                "value": "Poista rivi"
              }]
            })
          })
        })
      }, 'remove') : /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableCell["default"], {
        children: "\xA0"
      }, 'remove') : [])]
    }, "row-".concat(rowNum, "-").concat(rev));
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_core.FormHelperText, {
      id: "".concat(idSchema.$id, "__description"),
      component: "span",
      children: description
    }), /*#__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.jsx)(_TableRow["default"], {
            children: tableHeaders()
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableBody["default"], {
          children: tableCells
        })]
      })
    }), tableAddAllowed && totalRows < tableRowMaximum && /*#__PURE__*/(0, _jsxRuntime.jsx)(_IconButton["default"], {
      "aria-label": intl.formatMessage({
        id: "06GmPX",
        defaultMessage: [{
          "type": 0,
          "value": "Lisää rivi"
        }]
      }),
      onClick: onAddRow,
      disabled: disabled || readonly,
      edge: "start",
      style: {
        margin: '5px'
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Add["default"], {
        alt: intl.formatMessage({
          id: "06GmPX",
          defaultMessage: [{
            "type": 0,
            "value": "Lisää rivi"
          }]
        })
      })
    })]
  });
}

var _default = function _default(_ref3) {
  var config = _ref3.config;
  return {
    schema: {
      format: 'table',
      type: 'object',
      properties: {
        table: {
          type: 'array',
          "default": [],
          items: {
            type: 'array',
            items: {
              type: 'string'
            }
          }
        }
      }
    },
    uiSchema: {
      'ui:field': TableField
    }
  };
};

exports["default"] = _default;
var name = (0, _reactIntl.defineMessage)({
  id: "4QvGOn",
  defaultMessage: [{
    "type": 0,
    "value": "Taulukko"
  }]
});
exports.name = name;
var validationMessages = (0, _intl.defineMessages)({
  emptyValue: {
    id: "WBQmgL",
    defaultMessage: [{
      "type": 0,
      "value": "\""
    }, {
      "type": 1,
      "value": "title"
    }, {
      "type": 0,
      "value": "\" ei saa sisältää tyhjiä soluja."
    }]
  }
});
var validators = {
  required: {
    name: (0, _reactIntl.defineMessage)({
      id: "WHQ4l+",
      defaultMessage: [{
        "type": 0,
        "value": "Pakollinen taulukko"
      }]
    }),
    fn: function fn(value, element) {
      var _value$table;

      if (value && ((_value$table = value.table) === null || _value$table === void 0 ? void 0 : _value$table.length) > 0) {
        var _iterator = (0, _createForOfIteratorHelper2["default"])(value.table),
            _step;

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

            var _iterator2 = (0, _createForOfIteratorHelper2["default"])(row),
                _step2;

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

                if (item === undefined || item === '') {
                  return validationMessages.emptyValue;
                }
              }
            } catch (err) {
              _iterator2.e(err);
            } finally {
              _iterator2.f();
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      } else {
        return validationMessages.emptyValue;
      }
    }
  }
};
exports.validators = validators;
var elementType = 'field';
exports.elementType = elementType;
//# sourceMappingURL=tableField.cjs.map