"use strict";

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

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

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

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

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

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

require("!style-loader!css-loader!react-dates/lib/css/_datepicker.css");

require("!style-loader!css-loader!./style.css");

var _moment = _interopRequireDefault(require("moment"));

require("moment/locale/fi");

require("moment/locale/sv");

var _react = require("react");

var _reactDates = require("react-dates");

require("react-dates/initialize");

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

var _dateFns = require("date-fns");

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

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _lodash = require("lodash");

var _phrases = require("../../../../lib/configToSchemas/types/date/phrases");

var _utils = require("../../../utils.cjs");

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

/* eslint import/no-webpack-loader-syntax: "off" */

/* eslint import/no-unresolved: "off" */
var useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    button: (0, _defineProperty2["default"])({
      marginRight: theme.spacing(1),
      marginLeft: theme.spacing(1)
    }, theme.breakpoints.down('xs'), {
      marginTop: theme.spacing(1),
      marginLeft: '0px'
    }),
    dateBox: (0, _defineProperty2["default"])({
      display: 'flex',
      alignItems: 'center'
    }, theme.breakpoints.down('xs'), {
      flexDirection: 'column',
      alignItems: 'start',
      '& input::placeholder': {
        fontSize: '13px'
      }
    })
  };
});

function DateRangePickerField(props) {
  var _uiSchema$uiOptions, _uiSchema$uiOptions2, _uiSchema$uiOptions2$;

  var idSchema = props.idSchema,
      onChange = props.onChange,
      schema = props.schema,
      formData = props.formData,
      uiSchema = props.uiSchema,
      required = props.required,
      rawErrors = props.rawErrors;

  var _uiSchema$uiOptions$ = (_uiSchema$uiOptions = uiSchema['ui:options']) === null || _uiSchema$uiOptions === void 0 ? void 0 : _uiSchema$uiOptions.element,
      description = _uiSchema$uiOptions$.description,
      help = _uiSchema$uiOptions$.help;

  var intl = (0, _reactIntl.useIntl)();

  var _useState = (0, _react.useState)(),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      focusedInput = _useState2[0],
      setFocusedInput = _useState2[1];

  var _props$uiSchema$uiOp = props.uiSchema['ui:options'],
      _props$uiSchema$uiOp$ = _props$uiSchema$uiOp.element,
      disableEnd = _props$uiSchema$uiOp$.disableEnd,
      disableStart = _props$uiSchema$uiOp$.disableStart,
      dateFormat = _props$uiSchema$uiOp.dateFormat;

  var handleFocusChange = function handleFocusChange(focusedInput) {
    return setFocusedInput(focusedInput);
  };

  var locale = intl.locale;
  var language = intl.locale.split('-')[0] !== 'en';
  var classes = useStyles();
  (0, _react.useEffect)(function () {
    _moment["default"].locale(locale);
  }, [locale]);

  var earliestEndDate = function earliestEndDate() {
    if ((disableEnd === null || disableEnd === void 0 ? void 0 : disableEnd.disableBefore.type) === 'noValue' && (disableStart === null || disableStart === void 0 ? void 0 : disableStart.disableBefore.type) !== 'noValue') {
      return beforeDay(disableStart.disableBefore);
    } else if ((disableEnd === null || disableEnd === void 0 ? void 0 : disableEnd.disableBefore.type) !== 'noValue' && (disableStart === null || disableStart === void 0 ? void 0 : disableStart.disableBefore.type) === 'noValue') {
      return beforeDay(disableEnd.disableBefore);
    } else if (beforeDay(disableStart.disableBefore) > beforeDay(disableEnd.disableBefore)) {
      return beforeDay(disableStart.disableBefore);
    } else {
      return beforeDay(disableEnd.disableBefore);
    }
  };

  var beforeDay = function beforeDay(date) {
    if (date.type !== undefined) {
      return date.type !== 'date' ? (0, _dateFns.sub)(new Date(), (0, _defineProperty2["default"])({}, date.type, date.numberValue)) : new Date(date.dateValue);
    } else {
      return null;
    }
  };

  var afterDay = function afterDay(date) {
    if (date.type !== undefined) {
      return date.type !== 'date' ? (0, _dateFns.add)(new Date(), (0, _defineProperty2["default"])({}, date.type, date.numberValue)) : new Date(date.dateValue);
    } else {
      return null;
    }
  };

  var ariaLabel = (0, _utils.getAriaLabel)(uiSchema === null || uiSchema === void 0 ? void 0 : (_uiSchema$uiOptions2 = uiSchema['ui:options']) === null || _uiSchema$uiOptions2 === void 0 ? void 0 : (_uiSchema$uiOptions2$ = _uiSchema$uiOptions2.element) === null || _uiSchema$uiOptions2$ === void 0 ? void 0 : _uiSchema$uiOptions2$.label, uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema['ui:options'], required, intl.formatMessage({
    id: "l4R23W",
    defaultMessage: [{
      "type": 0,
      "value": "Pakollinen kenttä"
    }]
  }));
  var ariaArray = [ariaLabel];

  if (description) {
    ariaArray.push(description);
  }

  if (help) {
    ariaArray.push(help);
  }

  if (rawErrors && rawErrors.length > 0) {
    ariaArray.push.apply(ariaArray, (0, _toConsumableArray2["default"])(rawErrors));
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: classes.dateBox,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactDates.DateRangePicker, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
      onDatesChange: function onDatesChange(_ref) {
        var startDate = _ref.startDate,
            endDate = _ref.endDate;
        return (startDate || endDate) && onChange({
          start: startDate === null || startDate === void 0 ? void 0 : startDate.format('YYYY-MM-DD'),
          end: endDate === null || endDate === void 0 ? void 0 : endDate.format('YYYY-MM-DD')
        });
      },
      onFocusChange: handleFocusChange,
      focusedInput: focusedInput,
      small: true,
      numberOfMonths: 1,
      "aria-label": ariaLabel,
      screenReaderInputMessage: ariaArray.join(', '),
      displayFormat: dateFormat !== null && dateFormat !== void 0 ? dateFormat : 'D.M.yyyy',
      disabled: schema.readOnly || uiSchema.readonly
    }, language ? {
      phrases: (0, _lodash.mapValues)(_phrases.DateRangePickerPhrases, function (message) {
        return intl.formatMessage(message);
      })
    } : {}), {}, {
      hideKeyboardShortcutsPanel: true,
      startDate: (formData === null || formData === void 0 ? void 0 : formData.start) === undefined ? null : (0, _moment["default"])(formData === null || formData === void 0 ? void 0 : formData.start),
      startDateId: idSchema.start.$id,
      startDatePlaceholderText: intl.formatMessage({
        id: "yFga8M",
        defaultMessage: [{
          "type": 0,
          "value": "Alkupäivä"
        }]
      }),
      endDate: (formData === null || formData === void 0 ? void 0 : formData.end) === undefined ? null : (0, _moment["default"])(formData === null || formData === void 0 ? void 0 : formData.end),
      endDateId: idSchema.end.$id,
      endDatePlaceholderText: intl.formatMessage({
        id: "l26Isu",
        defaultMessage: [{
          "type": 0,
          "value": "Loppupäivä"
        }]
      }),
      isOutsideRange: function isOutsideRange(m) {
        return focusedInput === 'startDate' ? (disableStart === null || disableStart === void 0 ? void 0 : disableStart.disableBefore.type) !== 'noValue' && m.isBefore(beforeDay(disableStart.disableBefore), 'day') || (disableStart === null || disableStart === void 0 ? void 0 : disableStart.disableAfter.type) !== 'noValue' && m.isAfter(afterDay(disableStart.disableAfter), 'day') : ((disableEnd === null || disableEnd === void 0 ? void 0 : disableEnd.disableBefore.type) !== 'noValue' || (disableStart === null || disableStart === void 0 ? void 0 : disableStart.disableBefore.type) !== 'noValue') && m.isBefore(earliestEndDate(), 'day') || (disableEnd === null || disableEnd === void 0 ? void 0 : disableEnd.disableAfter.type) !== 'noValue' && m.isAfter(afterDay(disableEnd.disableAfter), 'day');
      }
    })), (formData === null || formData === void 0 ? void 0 : formData.start) || (formData === null || formData === void 0 ? void 0 : formData.end) ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
      variant: "contained",
      color: "secondary",
      size: "small",
      className: classes.button,
      onClick: function onClick(value) {
        return value && onChange({
          start: undefined,
          end: undefined
        });
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
        id: "fVRBN+",
        defaultMessage: [{
          "type": 0,
          "value": "Tyhjennä"
        }]
      })
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {})]
  });
}

var _default = function _default(_ref2) {
  var _reviewProps$dateForm;

  var _ref2$config = _ref2.config,
      disableBefore = _ref2$config.disableBefore,
      disableAfter = _ref2$config.disableAfter,
      required = _ref2$config.required,
      list = _ref2$config.list,
      reviewProps = _ref2.reviewProps;
  return {
    schema: (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({
      type: 'object'
    }, required ? {
      required: ['start', 'end']
    } : undefined), list ? {
      "default": {}
    } : undefined), {}, {
      properties: {
        start: {
          format: 'date',
          type: 'string'
        },
        end: {
          format: 'date',
          type: 'string'
        }
      }
    }),
    uiSchema: {
      'ui:field': DateRangePickerField,
      'ui:options': {
        disableBefore: disableBefore,
        disableAfter: disableAfter,
        dateFormat: reviewProps === null || reviewProps === void 0 ? void 0 : (_reviewProps$dateForm = reviewProps.dateFormat) === null || _reviewProps$dateForm === void 0 ? void 0 : _reviewProps$dateForm.replaceAll('d', 'D')
      }
    }
  };
};

exports["default"] = _default;
var name = (0, _reactIntl.defineMessage)({
  id: "G3a8oG",
  defaultMessage: [{
    "type": 0,
    "value": "Päivämäärähaarukka"
  }]
});
exports.name = name;
var elementType = 'field';
exports.elementType = elementType;
//# sourceMappingURL=index.cjs.map