import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import { defineMessage, useIntl } from 'react-intl';
import { uniqueId } from 'lodash';
import { useState } from 'react';
import IconButton from '@material-ui/core/IconButton';
import AddIcon from '@material-ui/icons/Add';
import { makeStyles } from '@material-ui/core/styles';
import { utils } from '@visma/rjsf-core';
import { FormHelperText } from '@material-ui/core';
import MUIDataTable from "mui-datatables";
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import TextField from '@material-ui/core/TextField';
import { TableFooter } from '@mui/material';
import DeleteIcon from "@material-ui/icons/Delete.js";
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var useStyles = 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
    }
  }
});
export var calcTypeSign = {
  none: '',
  sum: ' (+)',
  minus: ' (-)',
  multiplication: ' (*)',
  fraction: ' (/)'
};
var tableLabel = 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 _toConsumableArray(Array(rows)).map(function (_, rowNum) {
    return _toConsumableArray(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$calcTableColum = field.calcTableColumns,
      calcTableColumns = _field$calcTableColum === void 0 ? [] : _field$calcTableColum;
  return calcTableColumns.length || 0;
};

var getColumnData = function getColumnData(data, column) {
  return data.map(function (row) {
    return row[column];
  }).filter(function (val) {
    return val !== null;
  }).map(function (val) {
    return typeof val === 'string' ? val.replace(',', '.') : val;
  }).filter(function (val) {
    return !isNaN(Number(val));
  }).map(function (val) {
    return parseFloat(val);
  }).filter(function (val) {
    return !isNaN(val);
  });
};

var sanitizeResult = function sanitizeResult(value) {
  return Number(value).toFixed(2).toString().replace('.', ',');
};

var calculateResult = function calculateResult(type, data) {
  if (data.length > 0) {
    switch (type) {
      case 'sum':
        return sanitizeResult(data.reduce(function (partialSum, next) {
          return partialSum + next;
        }));

      case 'multiplication':
        return sanitizeResult(data.reduce(function (partialSum, next) {
          return partialSum * next;
        }));

      case 'minus':
        return sanitizeResult(data.reduce(function (partialSum, next) {
          return partialSum - next;
        }));

      case 'fraction':
        return sanitizeResult(data.reduce(function (partialSum, next) {
          return partialSum / next;
        }));

      default:
        return '';
    }
  }

  return '';
};

function CalcTable(props) {
  var disabled = props.disabled,
      readonly = props.readonly,
      onChange = props.onChange,
      formData = props.formData,
      errorSchema = props.errorSchema,
      uiSchema = props.uiSchema,
      idSchema = props.idSchema,
      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$calcTableColu = config.calcTableColumns,
      calcTableColumns = _config$calcTableColu === void 0 ? [] : _config$calcTableColu,
      _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 = useIntl();

  var _useState = useState(uniqueId()),
      _useState2 = _slicedToArray(_useState, 2),
      rev = _useState2[0],
      setRev = _useState2[1];

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

  var tableColumns = function tableColumns(ignoreTitleColumn) {
    var columns = calcTableColumns.map(function (col) {
      return (col === null || col === void 0 ? void 0 : col.name) ? col.name + calcTypeSign[col.calcType] : "";
    });

    if (useRowTitles && !ignoreTitleColumn) {
      columns.unshift("");
    }

    return columns;
  };

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

  var makeRow = function makeRow(data, dataIndex, row, tableColumns) {
    var cells = tableColumns(true).map(function (_, colNum) {
      return /*#__PURE__*/_jsx(TableCell, {
        children: /*#__PURE__*/_jsx(TextField, {
          id: "".concat(id, "-").concat(dataIndex, "-").concat(colNum),
          style: {
            width: '100%'
          },
          variant: "outlined",
          size: "small",
          "aria-label": intl.formatMessage(tableLabel, {
            tableName: useLabel ? label : title,
            columnName: tableColumns[colNum],
            row: dataIndex + 1
          }),
          label: useLabel ? label : title,
          defaultValue: tableData[dataIndex][colNum],
          disabled: disabled,
          readOnly: readonly,
          onChange: function onChange(event) {
            tableData[dataIndex][colNum] = event.target.value || defaultValue;
            onPropertyChange(tableData);
          },
          InputProps: {
            classes: {
              formControl: classes.inputFormControl
            },
            'aria-describedby': ariaDescribedby
          },
          InputLabelProps: {
            htmlFor: "".concat(id, "-").concat(dataIndex, "-").concat(colNum),
            shrink: false,
            className: classes.inputLabelRoot
          }
        })
      }, "col-".concat(colNum));
    });

    if (useRowTitles) {
      cells.unshift( /*#__PURE__*/_jsx(TableCell, {
        style: {
          fontWeight: 'bold'
        },
        align: "right",
        children: rowTitles.length === 0 || dataIndex > rowTitles.length ? "" : rowTitles[dataIndex]
      }, 'cell-' + dataIndex + '-' + '-1'));
    }

    return /*#__PURE__*/_jsxs(TableRow, {
      children: [cells, tableData.length > tableRowMinimum ? dataIndex >= tableRowMinimum ? /*#__PURE__*/_jsx(TableCell, {
        children: /*#__PURE__*/_jsx(IconButton, {
          "aria-label": intl.formatMessage({
            id: "7A0Mm1",
            defaultMessage: [{
              "type": 0,
              "value": "Poista rivi"
            }]
          }),
          onClick: function onClick(_) {
            onRemoveRow(dataIndex);
          },
          disabled: disabled || readonly,
          children: /*#__PURE__*/_jsx(DeleteIcon, {
            alt: intl.formatMessage({
              id: "7A0Mm1",
              defaultMessage: [{
                "type": 0,
                "value": "Poista rivi"
              }]
            })
          })
        })
      }, 'remove') : /*#__PURE__*/_jsx(TableCell, {
        children: "\xA0"
      }, 'remove') : /*#__PURE__*/_jsx(_Fragment, {})]
    }, "row-".concat(dataIndex, "-").concat(rev));
  };

  var makeFooter = function makeFooter() {
    var cells = tableColumns(true).map(function (_, colNum) {
      return makeFooterCell(colNum);
    });

    if (useRowTitles) {
      cells.unshift( /*#__PURE__*/_jsx(TableCell, {}));
    }

    return /*#__PURE__*/_jsx(TableFooter, {
      children: /*#__PURE__*/_jsx(TableRow, {
        children: cells
      })
    });
  };

  var makeFooterCell = function makeFooterCell(colNum) {
    var column = calcTableColumns[colNum];
    var data = getColumnData(tableData, colNum);

    if (data.length === 0) {
      return /*#__PURE__*/_jsx(TableCell, {
        style: {
          fontWeight: 'bold'
        },
        align: "right",
        children: column.calcType !== 'none' ? '= ' : ''
      });
    }

    return /*#__PURE__*/_jsx(TableCell, {
      style: {
        fontWeight: 'bold'
      },
      align: "right",
      children: '= ' + calculateResult(column.calcType, data)
    }, "footer-col-".concat(colNum));
  };

  var options = {
    search: false,
    download: false,
    print: false,
    viewColumns: false,
    filter: false,
    sort: false,
    display: false,
    pagination: false,
    selectableRows: 'none',
    customRowRender: function customRowRender(data, dataIndex) {
      return makeRow(data, dataIndex, tableData[dataIndex], tableColumns);
    },
    customTableBodyFooterRender: function customTableBodyFooterRender() {
      return makeFooter();
    },
    textLabels: {
      body: {
        noMatch: intl.formatMessage({
          id: "UpIQEQ",
          defaultMessage: [{
            "type": 0,
            "value": "Ei näytettäviä rivejä. Lisää rivi painamalla + -painiketta taulukon alapuolella."
          }]
        })
      }
    }
  };

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

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

  var onPropertyChange = function onPropertyChange(tableData) {
    var resultRow = calcTableColumns.map(function (column, index) {
      return calculateResult(column.calcType, getColumnData(tableData, index));
    });
    onChange({
      table: tableData,
      resultRow: resultRow
    }, errorSchema);

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

  return /*#__PURE__*/_jsxs("div", {
    children: [/*#__PURE__*/_jsx(FormHelperText, {
      id: "".concat(idSchema.$id, "__description"),
      component: "span",
      children: description
    }), /*#__PURE__*/_jsx(MUIDataTable, {
      data: tableData,
      columns: tableColumns(),
      options: options
    }), tableAddAllowed && totalRows < tableRowMaximum && /*#__PURE__*/_jsx(IconButton, {
      "aria-label": intl.formatMessage({
        id: "06GmPX",
        defaultMessage: [{
          "type": 0,
          "value": "Lisää rivi"
        }]
      }),
      onClick: onAddRow,
      disabled: disabled || readonly,
      edge: "start",
      style: {
        margin: '5px'
      },
      children: /*#__PURE__*/_jsx(AddIcon, {
        alt: intl.formatMessage({
          id: "06GmPX",
          defaultMessage: [{
            "type": 0,
            "value": "Lisää rivi"
          }]
        })
      })
    })]
  });
}

export default (function (_ref3) {
  var config = _ref3.config;
  return {
    schema: {
      format: 'table',
      type: 'object',
      properties: {
        resultRow: {
          type: 'array',
          "default": [],
          items: {
            type: 'string'
          }
        },
        table: {
          type: 'array',
          "default": [],
          items: {
            type: 'array',
            items: {
              type: 'string'
            }
          }
        }
      }
    },
    uiSchema: {
      'ui:field': CalcTable
    }
  };
});
export var name = defineMessage({
  id: "2SowsK",
  defaultMessage: [{
    "type": 0,
    "value": "Laskentataulukko"
  }]
});
export var elementType = 'field';
//# sourceMappingURL=calcTable.js.map