import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { defineMessage, useIntl } from 'react-intl';
import { utils } from '@visma/rjsf-core';
import { useContext, useEffect } from 'react';
import { useFields } from '../../api';
import sift from 'sift';

var getRepeatableFormgroupElementKeys = function getRepeatableFormgroupElementKeys(formdata, originalElements) {
  var elementKeys = [];
  var formDataKeys = Object.keys(formdata !== null && formdata !== void 0 ? formdata : {});
  formDataKeys.forEach(function (key) {
    var _element$filter, _element$filter2, _element$filter2$show;

    var element = originalElements.find(function (el) {
      return el.key === key;
    });

    if (element && (!((_element$filter = element.filter) === null || _element$filter === void 0 ? void 0 : _element$filter.show) || ((_element$filter2 = element.filter) === null || _element$filter2 === void 0 ? void 0 : (_element$filter2$show = _element$filter2.show) === null || _element$filter2$show === void 0 ? void 0 : _element$filter2$show.query) && sift(element.filter.show.query)(formdata))) {
      elementKeys.push(key);
    }
  });
  return elementKeys;
};

var getUsableFormData = function getUsableFormData(id, element, rootSchema, formData) {
  if (element.containingFormgroup) {
    for (var _i = 0, _Object$keys = Object.keys(rootSchema.properties); _i < _Object$keys.length; _i++) {
      var _formgroupConfig$item, _formgroupConfig$orig;

      var key = _Object$keys[_i];
      var formgroupConfig = rootSchema.properties[key];

      if (formgroupConfig.items && ((_formgroupConfig$item = formgroupConfig.items.originalConfig) === null || _formgroupConfig$item === void 0 ? void 0 : _formgroupConfig$item.id) === element.containingFormgroup) {
        var data = formData[key][id.substring(key.length + 6).split('_')[0]];
        return {
          usableFormData: data,
          existingDataKeys: getRepeatableFormgroupElementKeys(data, formgroupConfig.items.originalConfig.elements)
        };
      } else if ((formgroupConfig === null || formgroupConfig === void 0 ? void 0 : (_formgroupConfig$orig = formgroupConfig.originalConfig) === null || _formgroupConfig$orig === void 0 ? void 0 : _formgroupConfig$orig.id) === element.containingFormgroup) {
        return {
          usableFormData: formData[key],
          existingDataKeys: Object.keys(formgroupConfig === null || formgroupConfig === void 0 ? void 0 : formgroupConfig.properties)
        };
      }
    }
  }

  return {
    usableFormData: formData,
    existingDataKeys: Object.keys(rootSchema.properties)
  };
};

function Compose(props) {
  var _props$uiSchema, _props$uiSchema$uiOp, _props$registry;

  var intl = useIntl();

  var _useContext = useContext(utils.Context),
      formData = _useContext.formData;

  var fields = useFields();
  var element = (_props$uiSchema = props.uiSchema) === null || _props$uiSchema === void 0 ? void 0 : (_props$uiSchema$uiOp = _props$uiSchema['ui:options']) === null || _props$uiSchema$uiOp === void 0 ? void 0 : _props$uiSchema$uiOp.element;

  var _getUsableFormData = getUsableFormData(props.id, element, (_props$registry = props.registry) === null || _props$registry === void 0 ? void 0 : _props$registry.rootSchema, formData),
      usableFormData = _getUsableFormData.usableFormData,
      existingDataKeys = _getUsableFormData.existingDataKeys;

  useEffect(function () {
    var _props$options = props.options,
        values = _props$options.values,
        separator = _props$options.separator;
    var composedField = values.map(function (value) {
      var _ref = value ? value.split('.') : ['error', 'error'],
          _ref2 = _slicedToArray(_ref, 2),
          key = _ref2[0],
          id = _ref2[1];

      return key === 'error' ? {
        value: undefined
      } : {
        value: usableFormData === null || usableFormData === void 0 ? void 0 : usableFormData[key],
        key: key,
        id: parseInt(id)
      };
    }).filter(function (data) {
      return data.value !== undefined;
    }).map(function getStringValue(data) {
      var _field$choices$find, _choice$enumNames, _data$value$start, _data$value$end;

      var field = fields.find(function (field) {
        return field._id === data.id;
      });

      if (!field || !existingDataKeys.includes(data.key)) {
        return undefined;
      }

      if (Array.isArray(data.value)) {
        var listValue = data.value.map(function (dataValue) {
          return getStringValue(_objectSpread(_objectSpread({}, data), {}, {
            value: dataValue
          }));
        });
        return listValue.length > 0 ? listValue.join(separator) : undefined;
      } else {
        switch (field.type) {
          case 'select':
          case 'multiselect':
            var choice = (_field$choices$find = field.choices.find(function (choice) {
              return choice["enum"] === data.value;
            })) !== null && _field$choices$find !== void 0 ? _field$choices$find : field.choices[data.value];
            return (_choice$enumNames = choice === null || choice === void 0 ? void 0 : choice.enumNames) !== null && _choice$enumNames !== void 0 ? _choice$enumNames : data.value;

          case 'boolean':
            if (data.value) {
              return field.yes && field.yes !== '' ? field.yes : intl.formatMessage({
                id: "4ajajg",
                defaultMessage: [{
                  "type": 0,
                  "value": "Kyllä"
                }]
              });
            } else {
              return field.no && field.no !== '' ? field.no : intl.formatMessage({
                id: "JVSOMe",
                defaultMessage: [{
                  "type": 0,
                  "value": "Ei"
                }]
              });
            }

          case 'consent':
            if (data.value) {
              return field.yes && field.yes !== '' ? field.yes : intl.formatMessage({
                id: "F0dHQ0",
                defaultMessage: [{
                  "type": 0,
                  "value": "Hyväksyn"
                }]
              });
            } else {
              return undefined;
            }

          case 'dateRange':
            return "".concat((_data$value$start = data.value.start) !== null && _data$value$start !== void 0 ? _data$value$start : '', " - ").concat((_data$value$end = data.value.end) !== null && _data$value$end !== void 0 ? _data$value$end : '');

          case 'text':
          case 'textarea':
          case 'richtext':
          case 'email':
          case 'number':
          case 'password':
          case 'range':
          case 'bmi':
          case 'date':
            return data.value;

          default:
            return undefined;
        }
      }
    }).filter(function (data) {
      return data !== undefined;
    }).join(separator);
    setTimeout(function () {
      props.onChange(composedField);
    });
  }, [usableFormData, props.options, formData, fields]);
  return null;
}

export default (function (props) {
  var _props$config = props.config,
      _props$config$compose = _props$config.composeValues,
      composeValues = _props$config$compose === void 0 ? [] : _props$config$compose,
      _props$config$compose2 = _props$config.composeSeparator,
      composeSeparator = _props$config$compose2 === void 0 ? '' : _props$config$compose2,
      type = _props$config.type;
  return {
    schema: {
      type: 'string',
      additionalType: type
    },
    uiSchema: {
      'ui:widget': Compose,
      'ui:options': {
        values: composeValues,
        separator: composeSeparator
      }
    }
  };
});
export var name = defineMessage({
  id: "nYaKFF",
  defaultMessage: [{
    "type": 0,
    "value": "Koottu kenttä"
  }]
});
export var elementType = 'element';
//# sourceMappingURL=compose.js.map