import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { utils } from '@visma/rjsf-core';
import { get } from 'lodash';
import { useContext, useEffect, useState } from 'react';
import { defineMessage, useIntl } from 'react-intl';
import { Typography } from '@material-ui/core';
import bmi_male from './bmi_male';
import bmi_female from './bmi_female';
import { jsx as _jsx } from "react/jsx-runtime";

var getTable = function getTable(csvTableString) {
  var csvTableArray = csvTableString.split('\n');
  var keys = csvTableArray[0].split(',');
  var finalTableArray = csvTableArray.slice(1, csvTableArray.length).map(function (item) {
    var object = {};
    var itemArray = item.split(',');

    for (var index in keys) {
      object[keys[index]] = Number(itemArray[index]);
    }

    return object;
  });
  return finalTableArray;
};

var getChildBmi = function getChildBmi(age, bmi, table) {
  var row = table.find(function (el) {
    return el.age === Math.round((age + Number.EPSILON) * 100) / 100;
  });

  if (row) {
    var mu = row.mu,
        sigma = row.sigma,
        nu = row.nu; // Käytetään vertailuarvoina 18 vuotiaan mu, sigma ja nu arvoja

    var _table$find = table.find(function (el) {
      return el.age === 18;
    }),
        M = _table$find.mu,
        S = _table$find.sigma,
        L = _table$find.nu;

    var zScore = (Math.pow(bmi / mu, nu) - 1) / (nu * sigma);
    var childBmi = M * Math.pow(1 + L * S * zScore, 1 / L);
    return childBmi;
  }

  return NaN;
};

function Bmi(props) {
  var intl = useIntl();

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

  var path = props.id.split('_').slice(1, -1);

  var _useState = useState(props.value),
      _useState2 = _slicedToArray(_useState, 2),
      data = _useState2[0],
      setData = _useState2[1];

  useEffect(function () {
    setTimeout(function () {
      props.onChange(isNaN(data) ? undefined : data.toFixed(2));
    });
  }, [data]);
  useEffect( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var data, height, weight, bmi, gender, birthday, measuringDay, age, birthdayDate, measuringDayDate, table, childBmi;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            data = get(formData, path);
            height = data ? data[props.options.heightFieldKey] : formData ? formData[props.options.heightFieldKey] : null;
            weight = data ? data[props.options.weightFieldKey] : formData ? formData[props.options.weightFieldKey] : null;
            bmi = !isNaN(height) && !isNaN(weight) ? weight / (height * height / 10000) : NaN;

            if (props.options.type === 'child') {
              gender = data ? data[props.options.genderFieldKey] : formData ? formData[props.options.genderFieldKey] : null;
              birthday = data ? data[props.options.birthdayFieldKey] : formData ? formData[props.options.birthdayFieldKey] : null;
              measuringDay = data ? data[props.options.measuringDayFieldKey] : formData ? formData[props.options.measuringDayFieldKey] : null;

              if (birthday && measuringDay) {
                try {
                  birthdayDate = new Date(birthday);
                  measuringDayDate = new Date(measuringDay);
                  age = (measuringDayDate - birthdayDate) / (1000 * 60 * 60 * 24 * 365.25);
                } catch (e) {
                  console.error(e);
                }
              }

              if (gender !== undefined && age && !Number.isNaN(bmi)) {
                table = gender === '1' ? bmi_female : bmi_male;
                childBmi = getChildBmi(age, bmi, getTable(table));
                setData(childBmi);
              } else {
                setTimeout(function () {
                  setData(NaN);
                });
              }
            } else {
              setTimeout(function () {
                setData(bmi);
              });
            }

          case 5:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [formData, path, props]);

  if (!isNaN(props.value) && props.value) {
    var valueString = intl.formatMessage({
      id: "jZHTxP",
      defaultMessage: [{
        "type": 1,
        "value": "bmi"
      }, {
        "type": 0,
        "value": " kg/m²"
      }]
    }, {
      bmi: props.value
    });
    return /*#__PURE__*/_jsx("span", {
      "aria-label": "".concat(intl.formatMessage({
        id: "zHNS3q",
        defaultMessage: [{
          "type": 0,
          "value": "Painoindeksi"
        }]
      }), ": ").concat(valueString),
      children: valueString
    });
  }

  return /*#__PURE__*/_jsx(Typography, {
    children: "-"
  });
}

export default (function (props) {
  var _props$config$bmiFiel, _props$config, _props$config$bmiFiel2, _props$config$bmiFiel3, _props$config2, _props$config2$bmiFie, _props$config3, _props$config3$bmiFie, _props$config4, _props$config4$bmiFie, _props$config5, _props$config5$bmiFie, _props$config6, _props$config6$bmiFie;

  var heightFieldKey = (_props$config$bmiFiel = (_props$config = props.config) === null || _props$config === void 0 ? void 0 : (_props$config$bmiFiel2 = _props$config.bmiFieldKeys) === null || _props$config$bmiFiel2 === void 0 ? void 0 : _props$config$bmiFiel2.heightFieldKey) !== null && _props$config$bmiFiel !== void 0 ? _props$config$bmiFiel : 0;
  var weightFieldKey = (_props$config$bmiFiel3 = (_props$config2 = props.config) === null || _props$config2 === void 0 ? void 0 : (_props$config2$bmiFie = _props$config2.bmiFieldKeys) === null || _props$config2$bmiFie === void 0 ? void 0 : _props$config2$bmiFie.weightFieldKey) !== null && _props$config$bmiFiel3 !== void 0 ? _props$config$bmiFiel3 : 1;
  var genderFieldKey = (_props$config3 = props.config) === null || _props$config3 === void 0 ? void 0 : (_props$config3$bmiFie = _props$config3.bmiFieldKeys) === null || _props$config3$bmiFie === void 0 ? void 0 : _props$config3$bmiFie.genderFieldKey;
  var birthdayFieldKey = (_props$config4 = props.config) === null || _props$config4 === void 0 ? void 0 : (_props$config4$bmiFie = _props$config4.bmiFieldKeys) === null || _props$config4$bmiFie === void 0 ? void 0 : _props$config4$bmiFie.birthdayFieldKey;
  var measuringDayFieldKey = (_props$config5 = props.config) === null || _props$config5 === void 0 ? void 0 : (_props$config5$bmiFie = _props$config5.bmiFieldKeys) === null || _props$config5$bmiFie === void 0 ? void 0 : _props$config5$bmiFie.measuringDayFieldKey;
  var type = (_props$config6 = props.config) === null || _props$config6 === void 0 ? void 0 : (_props$config6$bmiFie = _props$config6.bmiFieldKeys) === null || _props$config6$bmiFie === void 0 ? void 0 : _props$config6$bmiFie.bmiType;
  return {
    schema: {
      type: 'string'
    },
    uiSchema: {
      'ui:widget': Bmi,
      'ui:options': {
        heightFieldKey: heightFieldKey,
        weightFieldKey: weightFieldKey,
        genderFieldKey: genderFieldKey,
        birthdayFieldKey: birthdayFieldKey,
        measuringDayFieldKey: measuringDayFieldKey,
        type: type,
        unit: 'kg/m²'
      }
    }
  };
});
export var name = defineMessage({
  id: "zHNS3q",
  defaultMessage: [{
    "type": 0,
    "value": "Painoindeksi"
  }]
});
export var elementType = 'field';
//# sourceMappingURL=bmi.js.map