"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.MonthPicker = void 0;

require("core-js/modules/es.array.includes.js");

var _propTypes = _interopRequireDefault(require("prop-types"));

var _Button = _interopRequireDefault(require("../Button/Button"));

var _Choice = _interopRequireDefault(require("../ChoiceList/Choice"));

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _getMonthNames = require("./getMonthNames");

var _i18n = require("../i18n");

var _FormLabel = require("../FormLabel");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var monthNumbers = function () {
  var months = [];

  for (var m = 1; m <= _getMonthNames.NUM_MONTHS; m++) {
    months.push(m);
  }

  return months;
}();

var MonthPicker = function MonthPicker(props) {
  var _props$locale, _props$defaultSelecte, _props$disabledMonths, _props$selectAllText, _props$clearAllText;

  var locale = (_props$locale = props.locale) !== null && _props$locale !== void 0 ? _props$locale : (0, _i18n.fallbackLocale)((0, _i18n.getLanguage)(), 'US');
  var months = (0, _getMonthNames.getMonthNames)(locale);
  var monthsLong = (0, _getMonthNames.getMonthNames)(locale, false);
  var isControlled = props.selectedMonths !== undefined;

  var _useState = (0, _react.useState)((_props$defaultSelecte = props.defaultSelectedMonths) !== null && _props$defaultSelecte !== void 0 ? _props$defaultSelecte : []),
      _useState2 = _slicedToArray(_useState, 2),
      selectedMonthsState = _useState2[0],
      setSelectedMonthsState = _useState2[1];

  var selectedMonths = isControlled ? props.selectedMonths : selectedMonthsState;
  var disabledMonths = (_props$disabledMonths = props.disabledMonths) !== null && _props$disabledMonths !== void 0 ? _props$disabledMonths : [];

  if (props.locale) {
    console.warn("[Deprecated]: Please remove the 'locale' prop in <MonthPicker> in favor of global language setting. This prop is deprecated and will be removed in a future release.");
  }

  function handleChange(event) {
    if (props.onChange) {
      props.onChange(event);
    }

    if (!isControlled) {
      var month = parseInt(event.target.value);
      var newSelectedMonths = selectedMonths.slice();

      if (newSelectedMonths.includes(month)) {
        newSelectedMonths.splice(newSelectedMonths.indexOf(month), 1);
      } else {
        newSelectedMonths.push(month);
      }

      setSelectedMonthsState(newSelectedMonths);
    }
  }

  function handleSelectAll() {
    if (props.onSelectAll) {
      props.onSelectAll();
    }

    if (!isControlled) {
      setSelectedMonthsState(monthNumbers.filter(function (m) {
        return !disabledMonths.includes(m);
      }));
    }
  }

  function handleClearAll() {
    if (props.onClearAll) {
      props.onClearAll();
    }

    if (!isControlled) {
      setSelectedMonthsState([]);
    }
  }

  var selectAllPressed = selectedMonths.length === _getMonthNames.NUM_MONTHS - disabledMonths.length;
  var clearAllPressed = selectedMonths.length === 0;

  var _useFormLabel = (0, _FormLabel.useFormLabel)(_objectSpread(_objectSpread({}, props), {}, {
    className: (0, _classnames.default)('ds-c-month-picker', props.className),
    labelComponent: 'legend',
    wrapperIsFieldset: true
  })),
      labelProps = _useFormLabel.labelProps,
      wrapperProps = _useFormLabel.wrapperProps,
      bottomError = _useFormLabel.bottomError;

  return /*#__PURE__*/_react.default.createElement("fieldset", wrapperProps, /*#__PURE__*/_react.default.createElement(_FormLabel.FormLabel, labelProps), /*#__PURE__*/_react.default.createElement("div", {
    className: "ds-c-month-picker__buttons ds-u-clearfix"
  }, /*#__PURE__*/_react.default.createElement(_Button.default, {
    "aria-pressed": selectAllPressed,
    size: "small",
    className: "ds-c-month-picker__button",
    onClick: handleSelectAll,
    onDark: props.inversed,
    variation: props.buttonVariation
  }, (_props$selectAllText = props.selectAllText) !== null && _props$selectAllText !== void 0 ? _props$selectAllText : (0, _i18n.t)('monthPicker.selectAllText')), /*#__PURE__*/_react.default.createElement(_Button.default, {
    "aria-pressed": clearAllPressed,
    size: "small",
    className: "ds-c-month-picker__button",
    onClick: handleClearAll,
    onDark: props.inversed,
    variation: props.buttonVariation
  }, (_props$clearAllText = props.clearAllText) !== null && _props$clearAllText !== void 0 ? _props$clearAllText : (0, _i18n.t)('monthPicker.clearAllText'))), /*#__PURE__*/_react.default.createElement("div", {
    className: "ds-c-month-picker__months"
  }, /*#__PURE__*/_react.default.createElement("ol", {
    className: "ds-c-list--bare ds-c-month-picker__months-list"
  }, months.map(function (month, i) {
    return /*#__PURE__*/_react.default.createElement("li", {
      key: month
    }, /*#__PURE__*/_react.default.createElement(_Choice.default, {
      "aria-label": monthsLong[i],
      checked: selectedMonths.includes(i + 1),
      className: "ds-c-month-picker__month",
      disabled: disabledMonths.includes(i + 1),
      inversed: props.inversed,
      onChange: handleChange,
      name: props.name,
      type: "checkbox",
      value: i + 1,
      label: month
    }));
  }))), bottomError);
};

exports.MonthPicker = MonthPicker;
MonthPicker.propTypes = {
  /**
     * The `input` field's `name` attribute
     */
  name: _propTypes.default.string.isRequired,

  /**
     * @deprecated - This is now deprecated in favor of the global language setting. See guides/internationalization
     * @hide-prop [Deprecated]
     *
     * A [BCP 47 language tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation)
     * for month name localization. For example: Passing `es-US` as a value
     * will render month names in Spanish.
     */
  locale: _propTypes.default.string,

  /**
     * Additional classes to be added to the root element.
     */
  className: _propTypes.default.string,

  /**
     * Array of month numbers, where `1` is January, and any month included
     * is disabled for selection.
     */
  disabledMonths: _propTypes.default.arrayOf(_propTypes.default.number),

  /**
     * Array of month numbers, where `1` is January, and any month included
     * is selected. This will render a read-only field. If the field should
     * be mutable, use `defaultSelectedMonths`.
     */
  selectedMonths: _propTypes.default.arrayOf(_propTypes.default.number),

  /**
     * Array of month numbers, where `1` is January, and any month included
     * is selected by default. Sets the initial checked state for the 12 month
     * checkboxes. Use this for an uncontrolled component; otherwise, use the
     * `selectedMonths` property.
     */
  defaultSelectedMonths: _propTypes.default.arrayOf(_propTypes.default.number),

  /**
     * A callback function that's invoked when a month's checked state is changed.
     * Note: This callback is not called when a month is selected or deselected
     * via the "Select all" or "Clear all" buttons – use the `onSelectAll` and
     * `onClearAll` event handlers for those instances.
     */
  onChange: _propTypes.default.func,
  onSelectAll: _propTypes.default.func,
  onClearAll: _propTypes.default.func,

  /**
     * The text for the "Select all" button for internationalization
     */
  selectAllText: _propTypes.default.string,

  /**
     * The text for the "Clear all" button for internationalization
     */
  clearAllText: _propTypes.default.string
};
var _default = MonthPicker;
exports.default = _default;