import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import { TextField } from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';
import { utils } from '@visma/rjsf-core';
import produce from 'immer';
import { useContext } from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
export var types = ['select'];
export function AutocompleteSelectField(props) {
  return /*#__PURE__*/_jsx(Autocomplete, {
    options: props.schema.enumNames,
    value: props.schema.enumNames[props.schema["enum"].indexOf(props.formData)],
    onChange: function onChange(event, value) {
      return props.onChange(props.schema["enum"][props.schema.enumNames.indexOf(value)]);
    },
    getOptionSelected: function getOptionSelected(option, value) {
      return option === value;
    },
    renderInput: function renderInput(params) {
      return /*#__PURE__*/_jsx(TextField, _objectSpread({}, params));
    }
  });
}

var isSameType = function isSameType(a) {
  return function (b) {
    return (a === null || a === void 0 ? void 0 : a.type) === b.type;
  };
};

var isNotSameId = function isNotSameId(a) {
  return function (b) {
    return a.id !== b.id;
  };
};

function UniqueItemsInFormGroupList(props) {
  var _useContext = useContext(utils.Context),
      formData = _useContext.formData;

  var idParts = props.idSchema.$id.split('_');
  var index = Number(idParts[idParts.length - 2]);
  var elements = formData.elements;
  var element = elements[index];
  var illegalIds = elements.filter(isSameType(element)).filter(isNotSameId(element)).map(function (element) {
    return element.id;
  });
  var enumValues = [];
  var enumNames = []; // eslint-disable-next-line @super-template/no-loops/no-loops

  for (var i = 0; i < props.schema["enum"].length; ++i) {
    var enumValue = props.schema["enum"][i];

    if (!illegalIds.includes(enumValue)) {
      enumValues.push(enumValue);
      enumNames.push(props.schema.enumNames[i]);
    }
  }

  return /*#__PURE__*/_jsx(AutocompleteSelectField, _objectSpread({}, produce(props, function (props) {
    props.schema["enum"] = enumValues;
    props.schema.enumNames = enumNames;
  })));
}

export var converter = function converter(_ref) {
  var config = _ref.config;
  return function (props) {
    if (config.autocomplete) {
      var _props$uiSchema;

      (_props$uiSchema = props.uiSchema) !== null && _props$uiSchema !== void 0 ? _props$uiSchema : props.uiSchema = {};
      props.uiSchema['ui:field'] = config.uniqueItemsInFormGroupList ? UniqueItemsInFormGroupList : AutocompleteSelectField;
    }
  };
};
//# sourceMappingURL=selectAutocomplete.js.map