function _typeof(obj) { 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); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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; }

/*
Copyright (c) 2018 Uber Technologies, Inc.

This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import { ArrowLeft, ArrowRight } from '../icon/index.js';
import { Select } from '../select/index.js';
import { StyledHeader } from './styled-components.js';
import { addMonths, getMonth, getMonthInLocale, getYear, monthDisabledBefore, monthDisabledAfter, setMonth, setYear, subMonths } from './utils/index.js';
import { getOverrides, mergeOverrides } from '../helpers/overrides.js';

var CalendarHeader =
/*#__PURE__*/
function (_React$Component) {
  _inherits(CalendarHeader, _React$Component);

  function CalendarHeader() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, CalendarHeader);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(CalendarHeader)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleMonthChange", function (_ref) {
      var value = _ref.value;

      _this.props.onMonthChange({
        date: setMonth(_this.props.date, value[0].id)
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleYearChange", function (_ref2) {
      var value = _ref2.value;

      _this.props.onYearChange({
        date: setYear(_this.props.date, value[0].id)
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "increaseMonth", function () {
      _this.props.onMonthChange({
        date: addMonths(_this.props.date, 1)
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "decreaseMonth", function () {
      _this.props.onMonthChange({
        date: subMonths(_this.props.date, 1)
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setActive", function () {
      _this.props.setActiveState(true);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setInactive", function () {
      _this.props.setActiveState(false);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "renderPreviousMonthButton", function () {
      var _this$props = _this.props,
          date = _this$props.date,
          _this$props$overrides = _this$props.overrides,
          overrides = _this$props$overrides === void 0 ? {} : _this$props$overrides;
      var allPrevDaysDisabled = monthDisabledBefore(date, _this.props);

      if (allPrevDaysDisabled) {
        return;
      }

      var _getOverrides = getOverrides(overrides.PrevButton, ArrowLeft),
          _getOverrides2 = _slicedToArray(_getOverrides, 2),
          PrevButton = _getOverrides2[0],
          prevButtonProps = _getOverrides2[1];

      var clickHandler = _this.decreaseMonth;

      if (allPrevDaysDisabled) {
        clickHandler = null;
      }

      return React.createElement(PrevButton, _extends({
        role: "button",
        tabIndex: 0,
        overrides: {
          Svg: {
            style: {
              cursor: 'pointer'
            }
          }
        }
      }, prevButtonProps, {
        // Adding internal click handler last that means no custom click handler
        // can be added throught props overrides unless passing a component
        // replacement that handles internal handler an then calls its custom one
        // What we can do here is extract an onClick handler from `nextButtonProps`
        // and call it along with `this.increaseMonth` withing a handler that is created
        // on render
        onClick: clickHandler
      }));
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "renderNextMonthButton", function () {
      var _this$props2 = _this.props,
          date = _this$props2.date,
          _this$props2$override = _this$props2.overrides,
          overrides = _this$props2$override === void 0 ? {} : _this$props2$override;
      var allNextDaysDisabled = monthDisabledAfter(date, _this.props);

      if (allNextDaysDisabled) {
        return;
      }

      var _getOverrides3 = getOverrides(overrides.NextButton, ArrowRight),
          _getOverrides4 = _slicedToArray(_getOverrides3, 2),
          NextButton = _getOverrides4[0],
          nextButtonProps = _getOverrides4[1];

      var clickHandler = _this.increaseMonth; // The other option is to always provide a click handler and let customers
      // override its functionality based on the `$allPrevDaysDisabled` prop
      // in a custom NextButton component override
      // Their options would be to render `null` or not apply the components handler
      // on click or do nothing

      if (allNextDaysDisabled) {
        clickHandler = null;
      }

      return React.createElement(NextButton, _extends({
        role: "button",
        tabIndex: 0,
        overrides: {
          Svg: {
            style: {
              cursor: 'pointer'
            }
          }
        }
      }, nextButtonProps, {
        // Adding internal click handler last that means no custom click handler
        // can be added throught props overrides unless passing a component
        // replacement that handles internal handler an then calls its custom one
        // What we can do here is extract an onClick handler from `nextButtonProps`
        // and call it along with `this.increaseMonth` withing a handler that is created
        // on render
        onClick: clickHandler
      }));
    });

    return _this;
  }

  _createClass(CalendarHeader, [{
    key: "getSelectOverrides",
    value: function getSelectOverrides(_ref3) {
      var width = _ref3.width;
      return {
        ControlContainer: {
          style: function style(props) {
            var $isFocused = props.$isFocused,
                $isPseudoFocused = props.$isPseudoFocused,
                colors = props.$theme.colors;
            return {
              width: width,
              backgroundColor: $isFocused || $isPseudoFocused ? colors.primary500 : colors.primary,
              color: colors.white,
              borderColor: 'transparent'
            };
          }
        },
        IconsContainer: {
          style: {
            paddingRight: '0'
          }
        },
        SelectArrow: {
          style: function style(_ref4) {
            var colors = _ref4.$theme.colors;
            return {
              color: 'inherit'
            };
          }
        },
        ValueContainer: {
          style: function style(_ref5) {
            var sizing = _ref5.$theme.sizing;
            return {
              paddingTop: '0',
              paddingBottom: '0',
              paddingLeft: sizing.scale200,
              paddingRight: '0'
            };
          }
        },
        SingleValue: {
          style: function style(_ref6) {
            var sizing = _ref6.$theme.sizing;
            return {
              paddingTop: '0',
              paddingBottom: '0',
              paddingLeft: sizing.scale200,
              paddingRight: '0'
            };
          }
        }
      };
    }
  }, {
    key: "renderMonthDropdown",
    value: function renderMonthDropdown() {
      var _this$props3 = this.props,
          date = _this$props3.date,
          locale = _this$props3.locale,
          _this$props3$override = _this$props3.overrides,
          overrides = _this$props3$override === void 0 ? {} : _this$props3$override;

      var _getOverrides5 = getOverrides(overrides.MonthSelect, Select),
          _getOverrides6 = _slicedToArray(_getOverrides5, 2),
          MonthSelect = _getOverrides6[0],
          monthSelectProps = _getOverrides6[1];

      var selectOverrides = mergeOverrides(this.getSelectOverrides({
        width: '115px'
      }), // $FlowFixMe
      monthSelectProps && monthSelectProps.overrides);
      var monthOptions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(function (M) {
        return {
          id: M,
          label: getMonthInLocale(M, locale)
        };
      });
      return React.createElement(MonthSelect, _extends({
        clearable: false,
        value: [{
          id: getMonth(date)
        }],
        maxDropdownHeight: '300px',
        options: monthOptions,
        searchable: false
      }, monthSelectProps, {
        // Adding event handlers after customers overrides in order to
        // make sure the components functions as expected
        // We can extract the handlers from props overrides
        // and call it along with internal handlers by creating an inline handler
        onOpen: this.setInactive,
        onClose: this.setActive,
        onChange: this.handleMonthChange // internal and incoming overrides are merged above
        ,
        overrides: selectOverrides
      }));
    }
  }, {
    key: "renderYearDropdown",
    value: function renderYearDropdown() {
      var _this$props4 = this.props,
          date = _this$props4.date,
          minDate = _this$props4.minDate,
          maxDate = _this$props4.maxDate,
          _this$props4$override = _this$props4.overrides,
          overrides = _this$props4$override === void 0 ? {} : _this$props4$override;

      var _getOverrides7 = getOverrides(overrides.YearSelect, Select),
          _getOverrides8 = _slicedToArray(_getOverrides7, 2),
          YearSelect = _getOverrides8[0],
          yearSelectProps = _getOverrides8[1];

      var selectOverrides = mergeOverrides(this.getSelectOverrides({
        width: '80px'
      }), // $FlowFixMe
      yearSelectProps && yearSelectProps.overrides);
      var maxYear = maxDate ? getYear(maxDate) : 2100;
      var minYear = minDate ? getYear(minDate) : 1900;
      var yearOptions = [];

      for (var i = minYear; i <= maxYear; i++) {
        yearOptions.push({
          id: i,
          label: i
        });
      }

      return React.createElement(YearSelect, _extends({
        clearable: false,
        value: [{
          id: getYear(date)
        }],
        maxDropdownHeight: '300px',
        options: yearOptions,
        searchable: false
      }, yearSelectProps, {
        // Adding event handlers after customers overrides in order to
        // make sure the components functions as expected
        // We can extract the handlers from props overrides
        // and call it along with internal handlers by creating an inline handler
        onOpen: this.setInactive,
        onClose: this.setActive,
        onChange: this.handleYearChange // internal and incoming overrides are merged above
        ,
        overrides: selectOverrides
      }));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props$overrides2 = this.props.overrides,
          overrides = _this$props$overrides2 === void 0 ? {} : _this$props$overrides2;

      var _getOverrides9 = getOverrides(overrides.CalendarHeader, StyledHeader),
          _getOverrides10 = _slicedToArray(_getOverrides9, 2),
          CalendarHeader = _getOverrides10[0],
          calendarHeaderProps = _getOverrides10[1];

      return React.createElement(CalendarHeader, calendarHeaderProps, this.renderPreviousMonthButton(), this.renderMonthDropdown(), this.renderYearDropdown(), this.renderNextMonthButton());
    }
  }]);

  return CalendarHeader;
}(React.Component);

_defineProperty(CalendarHeader, "defaultProps", {
  date: new Date(),
  locale: null,
  maxDate: null,
  minDate: null,
  onMonthChange: function onMonthChange() {},
  onYearChange: function onYearChange() {},
  overrides: {},
  setActiveState: function setActiveState() {}
});

export { CalendarHeader as default };