import * as tslib_1 from "tslib";
import * as React from 'react';
import { BaseComponent, KeyCodes, css, getId, getRTL, getRTLSafeKeyCode, format, findIndex, find } from '../../Utilities';
import { DateRangeType } from '../../utilities/dateValues/DateValues';
import { FocusZone } from '../../FocusZone';
import { Icon } from '../../Icon';
import { addDays, addWeeks, addMonths, compareDates, compareDatePart, getDateRangeArray, isInDateRangeArray, getWeekNumber, getWeekNumbersInMonth, getMonthStart, getMonthEnd } from '../../utilities/dateMath/DateMath';
import * as stylesImport from './Calendar.scss';
var styles = stylesImport;
var DAYS_IN_WEEK = 7;
var CalendarDay = /** @class */ (function (_super) {
    tslib_1.__extends(CalendarDay, _super);
    function CalendarDay(props) {
        var _this = _super.call(this, props) || this;
        _this.days = {};
        _this._onKeyDown = function (callback, ev) {
            if (ev.which === KeyCodes.enter || ev.which === KeyCodes.space) {
                callback();
            }
        };
        _this._onDayKeyDown = function (originalDate, weekIndex, dayIndex) {
            return function (ev) {
                if (ev.which === KeyCodes.enter) {
                    _this._onSelectDate(originalDate, ev);
                }
                else {
                    _this._navigateMonthEdge(ev, originalDate, weekIndex, dayIndex);
                }
            };
        };
        _this._onDayMouseDown = function (originalDate, weekIndex, dayIndex, dateRangeType) {
            return function (ev) {
                // set the press styling
                if (dateRangeType === DateRangeType.Month) {
                    _this._applyFunctionToDayRefs(function (ref, day) {
                        if (ref && day.originalDate.getMonth() === originalDate.getMonth() && day.isInBounds) {
                            ref.classList.add(styles.dayPress);
                        }
                    });
                }
                else {
                    // week or work week view
                    _this._applyFunctionToDayRefs(function (ref, day, dayWeekIndex) {
                        if (ref && dayWeekIndex === weekIndex && day.isInBounds) {
                            ref.classList.add(styles.dayPress);
                            ref.classList.add(styles.dayIsHighlighted);
                        }
                        else if (ref) {
                            ref.classList.remove(styles.dayIsHighlighted);
                        }
                    });
                }
            };
        };
        _this._onDayMouseUp = function (originalDate, weekIndex, dayIndex, dateRangeType) {
            return function (ev) {
                // remove press styling
                if (dateRangeType === DateRangeType.Month) {
                    _this._applyFunctionToDayRefs(function (ref, day) {
                        if (ref && day.originalDate.getMonth() === originalDate.getMonth() && day.isInBounds) {
                            ref.classList.remove(styles.dayPress);
                        }
                    });
                }
                else {
                    // week or work week view
                    _this._applyFunctionToDayRefs(function (ref, day, dayWeekIndex) {
                        if (ref && dayWeekIndex === weekIndex && day.isInBounds) {
                            ref.classList.remove(styles.dayPress);
                        }
                    });
                }
            };
        };
        _this._onDayMouseOver = function (originalDate, weekIndex, dayIndex, dateRangeType) {
            return function (ev) {
                // set the hover styling on every day in the same month
                if (dateRangeType === DateRangeType.Month) {
                    _this._applyFunctionToDayRefs(function (ref, day) {
                        if (ref && day.originalDate.getMonth() === originalDate.getMonth() && day.isInBounds) {
                            ref.classList.add(styles.dayHover);
                        }
                    });
                }
                else {
                    // week or work week view
                    _this._applyFunctionToDayRefs(function (ref, day, dayWeekIndex) {
                        if (ref && dayWeekIndex === weekIndex && day.isInBounds) {
                            ref.classList.add(styles.dayHover);
                        }
                    });
                }
            };
        };
        _this._onDayMouseLeave = function (originalDate, weekIndex, dayIndex, dateRangeType) {
            return function (ev) {
                // remove the hover and pressed styling
                if (dateRangeType === DateRangeType.Month) {
                    _this._applyFunctionToDayRefs(function (ref, day) {
                        if (ref && day.originalDate.getMonth() === originalDate.getMonth() && day.isInBounds) {
                            ref.classList.remove(styles.dayHover);
                        }
                    });
                }
                else {
                    // week or work week view
                    _this._applyFunctionToDayRefs(function (ref, day, dayWeekIndex) {
                        if (ref && dayWeekIndex === weekIndex && day.isInBounds) {
                            ref.classList.remove(styles.dayHover);
                        }
                    });
                }
            };
        };
        _this._onTableMouseLeave = function (ev) {
            if (ev.target.contains &&
                ev.relatedTarget &&
                ev.relatedTarget.contains &&
                ev.target.contains(ev.relatedTarget)) {
                return;
            }
            _this._applyFunctionToDayRefs(function (ref, day) {
                if (ref) {
                    ref.classList.remove(styles.dayHover);
                    ref.classList.remove(styles.dayPress);
                }
            });
        };
        _this._onTableMouseUp = function (ev) {
            if (ev.target.contains &&
                ev.relatedTarget &&
                ev.relatedTarget.contains &&
                ev.target.contains(ev.relatedTarget)) {
                return;
            }
            _this._applyFunctionToDayRefs(function (ref, day) {
                if (ref) {
                    ref.classList.remove(styles.dayPress);
                }
            });
        };
        _this._onSelectDate = function (selectedDate, ev) {
            var _a = _this.props, onSelectDate = _a.onSelectDate, dateRangeType = _a.dateRangeType, firstDayOfWeek = _a.firstDayOfWeek, navigatedDate = _a.navigatedDate, autoNavigateOnSelection = _a.autoNavigateOnSelection, minDate = _a.minDate, maxDate = _a.maxDate, workWeekDays = _a.workWeekDays;
            if (ev) {
                ev.stopPropagation();
            }
            var dateRange = getDateRangeArray(selectedDate, dateRangeType, firstDayOfWeek, workWeekDays);
            if (dateRangeType !== DateRangeType.Day) {
                dateRange = _this._getBoundedDateRange(dateRange, minDate, maxDate);
            }
            dateRange = dateRange.filter(function (d) {
                return !_this._getIsRestrictedDate(d);
            });
            if (onSelectDate) {
                onSelectDate(selectedDate, dateRange);
            }
            // Navigate to next or previous month if needed
            if (autoNavigateOnSelection && selectedDate.getMonth() !== navigatedDate.getMonth()) {
                var compareResult = compareDatePart(selectedDate, navigatedDate);
                if (compareResult < 0) {
                    _this._onSelectPrevMonth();
                }
                else if (compareResult > 0) {
                    _this._onSelectNextMonth();
                }
            }
        };
        _this._onSelectNextMonth = function () {
            _this.props.onNavigateDate(addMonths(_this.props.navigatedDate, 1), false);
        };
        _this._onSelectPrevMonth = function () {
            _this.props.onNavigateDate(addMonths(_this.props.navigatedDate, -1), false);
        };
        _this._onClose = function () {
            if (_this.props.onDismiss) {
                _this.props.onDismiss();
            }
        };
        _this._onHeaderSelect = function () {
            var onHeaderSelect = _this.props.onHeaderSelect;
            if (onHeaderSelect) {
                onHeaderSelect(true);
            }
        };
        _this._onHeaderKeyDown = function (ev) {
            var onHeaderSelect = _this.props.onHeaderSelect;
            if (onHeaderSelect && (ev.which === KeyCodes.enter || ev.which === KeyCodes.space)) {
                onHeaderSelect(true);
            }
        };
        _this._onPrevMonthKeyDown = function (ev) {
            if (ev.which === KeyCodes.enter) {
                _this._onKeyDown(_this._onSelectPrevMonth, ev);
            }
        };
        _this._onNextMonthKeyDown = function (ev) {
            if (ev.which === KeyCodes.enter) {
                _this._onKeyDown(_this._onSelectNextMonth, ev);
            }
        };
        _this._onCloseButtonKeyDown = function (ev) {
            if (ev.which === KeyCodes.enter) {
                _this._onKeyDown(_this._onClose, ev);
            }
        };
        _this.state = {
            activeDescendantId: getId('DatePickerDay-active'),
            weeks: _this._getWeeks(props)
        };
        _this._onSelectNextMonth = _this._onSelectNextMonth.bind(_this);
        _this._onSelectPrevMonth = _this._onSelectPrevMonth.bind(_this);
        _this._onClose = _this._onClose.bind(_this);
        return _this;
    }
    // tslint:disable-next-line function-name
    CalendarDay.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        this.setState({
            weeks: this._getWeeks(nextProps)
        });
    };
    CalendarDay.prototype.render = function () {
        var _a, _b;
        var _this = this;
        var _c = this.state, activeDescendantId = _c.activeDescendantId, weeks = _c.weeks;
        var _d = this.props, firstDayOfWeek = _d.firstDayOfWeek, strings = _d.strings, navigatedDate = _d.navigatedDate, selectedDate = _d.selectedDate, dateRangeType = _d.dateRangeType, navigationIcons = _d.navigationIcons, showWeekNumbers = _d.showWeekNumbers, firstWeekOfYear = _d.firstWeekOfYear, dateTimeFormatter = _d.dateTimeFormatter, minDate = _d.minDate, maxDate = _d.maxDate, showCloseButton = _d.showCloseButton, allFocusable = _d.allFocusable;
        var dayPickerId = getId('DatePickerDay-dayPicker');
        var monthAndYearId = getId('DatePickerDay-monthAndYear');
        var leftNavigationIcon = navigationIcons.leftNavigation;
        var rightNavigationIcon = navigationIcons.rightNavigation;
        var closeNavigationIcon = navigationIcons.closeIcon;
        var weekNumbers = showWeekNumbers ? getWeekNumbersInMonth(weeks.length, firstDayOfWeek, firstWeekOfYear, navigatedDate) : null;
        var selectedDateWeekNumber = showWeekNumbers ? getWeekNumber(selectedDate, firstDayOfWeek, firstWeekOfYear) : undefined;
        // When the month is highlighted get the corner dates so that styles can be added to them
        var weekCorners = this._getWeekCornerStyles(weeks, dateRangeType);
        // determine if previous/next months are in bounds
        var prevMonthInBounds = minDate ? compareDatePart(minDate, getMonthStart(navigatedDate)) < 0 : true;
        var nextMonthInBounds = maxDate ? compareDatePart(getMonthEnd(navigatedDate), maxDate) < 0 : true;
        return (React.createElement("div", { className: css('ms-DatePicker-dayPicker', styles.dayPicker, showWeekNumbers && 'ms-DatePicker-showWeekNumbers' && (getRTL() ? styles.showWeekNumbersRTL : styles.showWeekNumbers)), id: dayPickerId },
            React.createElement("div", { className: css('ms-DatePicker-header', styles.header) },
                React.createElement("div", { "aria-live": "polite", "aria-relevant": "text", "aria-atomic": "true", id: monthAndYearId, className: styles.monthAndYear }, this.props.onHeaderSelect ? (React.createElement("div", { className: css('ms-DatePicker-monthAndYear js-showMonthPicker', styles.headerToggleView), onClick: this._onHeaderSelect, onKeyDown: this._onHeaderKeyDown, "aria-label": dateTimeFormatter.formatMonthYear(navigatedDate, strings), role: "button", tabIndex: 0 }, dateTimeFormatter.formatMonthYear(navigatedDate, strings))) : (React.createElement("div", { className: css('ms-DatePicker-monthAndYear', styles.monthAndYear) }, dateTimeFormatter.formatMonthYear(navigatedDate, strings)))),
                React.createElement("div", { className: css('ms-DatePicker-monthComponents', styles.monthComponents) },
                    React.createElement("div", { className: css('ms-DatePicker-navContainer', styles.navContainer) },
                        React.createElement("button", { className: css('ms-DatePicker-prevMonth js-prevMonth', styles.prevMonth, (_a = {},
                                _a['ms-DatePicker-prevMonth--disabled ' + styles.prevMonthIsDisabled] = !prevMonthInBounds,
                                _a)), disabled: !allFocusable && !prevMonthInBounds, "aria-disabled": !prevMonthInBounds, onClick: prevMonthInBounds ? this._onSelectPrevMonth : undefined, onKeyDown: prevMonthInBounds ? this._onPrevMonthKeyDown : undefined, "aria-controls": dayPickerId, title: strings.prevMonthAriaLabel
                                ? strings.prevMonthAriaLabel + ' ' + strings.months[addMonths(navigatedDate, -1).getMonth()]
                                : undefined, role: "button", type: "button" },
                            React.createElement(Icon, { iconName: leftNavigationIcon })),
                        React.createElement("button", { className: css('ms-DatePicker-nextMonth js-nextMonth', styles.nextMonth, (_b = {},
                                _b['ms-DatePicker-nextMonth--disabled ' + styles.nextMonthIsDisabled] = !nextMonthInBounds,
                                _b)), disabled: !allFocusable && !nextMonthInBounds, "aria-disabled": !nextMonthInBounds, onClick: nextMonthInBounds ? this._onSelectNextMonth : undefined, onKeyDown: nextMonthInBounds ? this._onNextMonthKeyDown : undefined, "aria-controls": dayPickerId, title: strings.nextMonthAriaLabel
                                ? strings.nextMonthAriaLabel + ' ' + strings.months[addMonths(navigatedDate, 1).getMonth()]
                                : undefined, role: "button", type: "button" },
                            React.createElement(Icon, { iconName: rightNavigationIcon })),
                        showCloseButton && (React.createElement("button", { className: css('ms-DatePicker-closeButton js-closeButton', styles.closeButton), onClick: this._onClose, onKeyDown: this._onCloseButtonKeyDown, title: strings.closeButtonAriaLabel, role: "button", type: "button" },
                            React.createElement(Icon, { iconName: closeNavigationIcon })))))),
            React.createElement(FocusZone, null,
                React.createElement("table", { className: css('ms-DatePicker-table', styles.table), "aria-readonly": "true", "aria-multiselectable": "false", "aria-labelledby": monthAndYearId, "aria-activedescendant": activeDescendantId, role: "grid" },
                    React.createElement("thead", null,
                        React.createElement("tr", null,
                            showWeekNumbers && React.createElement("th", { className: css('ms-DatePicker-weekday', styles.weekday) }),
                            strings.shortDays.map(function (val, index) { return (React.createElement("th", { className: css('ms-DatePicker-weekday', styles.weekday), role: "columnheader", scope: "col", key: index, title: strings.days[(index + firstDayOfWeek) % DAYS_IN_WEEK], "aria-label": strings.days[(index + firstDayOfWeek) % DAYS_IN_WEEK], "data-is-focusable": allFocusable ? true : undefined }, strings.shortDays[(index + firstDayOfWeek) % DAYS_IN_WEEK])); }))),
                    React.createElement("tbody", { onMouseLeave: dateRangeType !== DateRangeType.Day ? this._onTableMouseLeave : undefined, onMouseUp: dateRangeType !== DateRangeType.Day ? this._onTableMouseUp : undefined }, weeks.map(function (week, weekIndex) {
                        var _a;
                        return (React.createElement("tr", { key: weekNumbers ? weekNumbers[weekIndex] : weekIndex },
                            showWeekNumbers && weekNumbers && (React.createElement("th", { className: css('ms-DatePicker-weekNumbers', 'ms-DatePicker-weekday', styles.weekday, styles.weekNumbers), key: weekIndex, title: weekNumbers && strings.weekNumberFormatString && format(strings.weekNumberFormatString, weekNumbers[weekIndex]), "aria-label": weekNumbers && strings.weekNumberFormatString && format(strings.weekNumberFormatString, weekNumbers[weekIndex]), scope: "row" },
                                React.createElement("div", { className: css('ms-DatePicker-day', styles.day, (_a = {},
                                        _a['ms-DatePicker-week--highlighted ' + styles.weekIsHighlighted] = selectedDateWeekNumber === weekNumbers[weekIndex],
                                        _a)) },
                                    React.createElement("span", null, weekNumbers[weekIndex])))),
                            week.map(function (day, dayIndex) {
                                var _a, _b;
                                var isNavigatedDate = compareDates(navigatedDate, day.originalDate);
                                return (React.createElement("td", { key: day.key, onClick: day.isInBounds ? day.onSelected : undefined, className: css(styles.dayWrapper, 'ms-DatePicker-day', _this._getHighlightedCornerStyle(weekCorners, dayIndex, weekIndex), (_a = {},
                                        _a['ms-DatePicker-weekBackground ' + styles.weekBackground] = day.isSelected && (dateRangeType === DateRangeType.Week || dateRangeType === DateRangeType.WorkWeek),
                                        _a['ms-DatePicker-dayBackground ' + styles.dayBackground] = dateRangeType === DateRangeType.Day,
                                        _a['ms-DatePicker-day--highlighted ' + styles.dayIsHighlighted] = day.isSelected && dateRangeType === DateRangeType.Day,
                                        _a['ms-DatePicker-day--infocus ' + styles.dayIsFocused] = day.isInBounds && day.isInMonth,
                                        _a['ms-DatePicker-day--outfocus ' + styles.dayIsUnfocused] = day.isInBounds && !day.isInMonth,
                                        _a[styles.daySelection] = dateRangeType === DateRangeType.Day,
                                        _a[styles.weekSelection] = dateRangeType === DateRangeType.Week || dateRangeType === DateRangeType.WorkWeek,
                                        _a[styles.monthSelection] = dateRangeType === DateRangeType.Month,
                                        _a)), ref: function (element) { return _this._setDayCellRef(element, day, isNavigatedDate); }, onMouseOver: dateRangeType !== DateRangeType.Day && day.isInBounds
                                        ? _this._onDayMouseOver(day.originalDate, weekIndex, dayIndex, dateRangeType)
                                        : undefined, onMouseLeave: dateRangeType !== DateRangeType.Day && day.isInBounds
                                        ? _this._onDayMouseLeave(day.originalDate, weekIndex, dayIndex, dateRangeType)
                                        : undefined, onMouseDown: dateRangeType !== DateRangeType.Day && day.isInBounds
                                        ? _this._onDayMouseDown(day.originalDate, weekIndex, dayIndex, dateRangeType)
                                        : undefined, onMouseUp: dateRangeType !== DateRangeType.Day && day.isInBounds
                                        ? _this._onDayMouseUp(day.originalDate, weekIndex, dayIndex, dateRangeType)
                                        : undefined, role: 'gridcell' },
                                    React.createElement("button", { key: day.key + 'button', onClick: day.isInBounds ? day.onSelected : undefined, className: css(styles.day, 'ms-DatePicker-day-button', (_b = {},
                                            _b['ms-DatePicker-day--disabled ' + styles.dayIsDisabled] = !day.isInBounds,
                                            _b['ms-DatePicker-day--today ' + styles.dayIsToday] = day.isToday,
                                            _b)), role: "gridcell", onKeyDown: _this._onDayKeyDown(day.originalDate, weekIndex, dayIndex), "aria-label": dateTimeFormatter.formatMonthDayYear(day.originalDate, strings), id: isNavigatedDate ? activeDescendantId : undefined, "aria-readonly": true, "aria-selected": day.isInBounds ? day.isSelected : undefined, "data-is-focusable": allFocusable || (day.isInBounds ? true : undefined), ref: function (element) { return _this._setDayRef(element, day, isNavigatedDate); }, disabled: !allFocusable && !day.isInBounds, "aria-disabled": !day.isInBounds, type: "button" },
                                        React.createElement("span", { "aria-hidden": "true" }, dateTimeFormatter.formatDay(day.originalDate)))));
                            })));
                    }))))));
    };
    CalendarDay.prototype.focus = function () {
        if (this.navigatedDay) {
            this.navigatedDay.tabIndex = 0;
            this.navigatedDay.focus();
        }
    };
    CalendarDay.prototype._setDayRef = function (element, day, isNavigatedDate) {
        if (isNavigatedDate) {
            this.navigatedDay = element;
        }
    };
    CalendarDay.prototype._setDayCellRef = function (element, day, isNavigatedDate) {
        this.days[day.key] = element;
    };
    CalendarDay.prototype._getWeekCornerStyles = function (weeks, dateRangeType) {
        var _this = this;
        var weekCornersStyled = {};
        switch (dateRangeType) {
            case DateRangeType.Month:
                /* need to handle setting all of the corners on arbitrarily shaped blobs
                      __
                   __|A |
                  |B |C |__
                  |D |E |F |
        
                  in this case, A needs top left rounded, top right rounded
                  B needs top left rounded
                  C doesn't need any rounding
                  D needs bottom left rounded
                  E doesn't need any rounding
                  F needs top right rounding
                */
                // if there's an item above, lose both top corners. Item below, lose both bottom corners, etc.
                weeks.forEach(function (week, weekIndex) {
                    week.forEach(function (day, dayIndex) {
                        var above = weeks[weekIndex - 1] &&
                            weeks[weekIndex - 1][dayIndex] &&
                            weeks[weekIndex - 1][dayIndex].originalDate.getMonth() === weeks[weekIndex][dayIndex].originalDate.getMonth();
                        var below = weeks[weekIndex + 1] &&
                            weeks[weekIndex + 1][dayIndex] &&
                            weeks[weekIndex + 1][dayIndex].originalDate.getMonth() === weeks[weekIndex][dayIndex].originalDate.getMonth();
                        var left = weeks[weekIndex][dayIndex - 1] &&
                            weeks[weekIndex][dayIndex - 1].originalDate.getMonth() === weeks[weekIndex][dayIndex].originalDate.getMonth();
                        var right = weeks[weekIndex][dayIndex + 1] &&
                            weeks[weekIndex][dayIndex + 1].originalDate.getMonth() === weeks[weekIndex][dayIndex].originalDate.getMonth();
                        var roundedTopLeft = !above && !left;
                        var roundedTopRight = !above && !right;
                        var roundedBottomLeft = !below && !left;
                        var roundedBottomRight = !below && !right;
                        var style = '';
                        if (roundedTopLeft) {
                            style = getRTL() ? style.concat(styles.topRightCornerDate + ' ') : style.concat(styles.topLeftCornerDate + ' ');
                        }
                        if (roundedTopRight) {
                            style = getRTL() ? style.concat(styles.topLeftCornerDate + ' ') : style.concat(styles.topRightCornerDate + ' ');
                        }
                        if (roundedBottomLeft) {
                            style = getRTL() ? style.concat(styles.bottomRightCornerDate + ' ') : style.concat(styles.bottomLeftCornerDate + ' ');
                        }
                        if (roundedBottomRight) {
                            style = getRTL() ? style.concat(styles.bottomLeftCornerDate + ' ') : style.concat(styles.bottomRightCornerDate + ' ');
                        }
                        if (!above) {
                            style = style.concat(styles.topDate + ' ');
                        }
                        if (!below) {
                            style = style.concat(styles.bottomDate + ' ');
                        }
                        if (!right) {
                            style = style.concat(styles.rightDate + ' ');
                        }
                        if (!left) {
                            style = style.concat(styles.leftdate + ' ');
                        }
                        weekCornersStyled[weekIndex + '_' + dayIndex] = style;
                    });
                });
                break;
            case DateRangeType.Week:
            case DateRangeType.WorkWeek:
                weeks.forEach(function (week, weekIndex) {
                    var minIndex = findIndex(week, function (item) {
                        return item.isInBounds;
                    });
                    var maxIndex = _this._findLastIndex(week, function (item) {
                        return item.isInBounds;
                    });
                    var leftStyle = styles.topLeftCornerDate + ' ' + styles.bottomLeftCornerDate;
                    var rightStyle = styles.topRightCornerDate + ' ' + styles.bottomRightCornerDate;
                    weekCornersStyled[weekIndex + '_' + minIndex] = getRTL() ? rightStyle : leftStyle;
                    weekCornersStyled[weekIndex + '_' + maxIndex] = getRTL() ? leftStyle : rightStyle;
                });
                break;
        }
        return weekCornersStyled;
    };
    CalendarDay.prototype._getHighlightedCornerStyle = function (weekCorners, dayIndex, weekIndex) {
        var cornerStyle = weekCorners[weekIndex + '_' + dayIndex] ? weekCorners[weekIndex + '_' + dayIndex] : '';
        return cornerStyle;
    };
    CalendarDay.prototype._navigateMonthEdge = function (ev, date, weekIndex, dayIndex) {
        var _a = this.props, minDate = _a.minDate, maxDate = _a.maxDate;
        var targetDate = undefined;
        if (weekIndex === 0 && ev.which === KeyCodes.up) {
            targetDate = addWeeks(date, -1);
        }
        else if (weekIndex === this.state.weeks.length - 1 && ev.which === KeyCodes.down) {
            targetDate = addWeeks(date, 1);
        }
        else if (dayIndex === 0 && ev.which === getRTLSafeKeyCode(KeyCodes.left)) {
            targetDate = addDays(date, -1);
        }
        else if (dayIndex === DAYS_IN_WEEK - 1 && ev.which === getRTLSafeKeyCode(KeyCodes.right)) {
            targetDate = addDays(date, 1);
        }
        // Don't navigate to out-of-bounds date
        if (targetDate &&
            (minDate ? compareDatePart(minDate, targetDate) < 1 : true) &&
            (maxDate ? compareDatePart(targetDate, maxDate) < 1 : true)) {
            this.props.onNavigateDate(targetDate, true);
            ev.preventDefault();
        }
    };
    CalendarDay.prototype._applyFunctionToDayRefs = function (func) {
        var _this = this;
        if (this.state.weeks) {
            this.state.weeks.map(function (week, weekIndex) {
                week.map(function (day) {
                    var ref = _this.days[day.key];
                    func(ref, day, weekIndex);
                });
            });
        }
    };
    CalendarDay.prototype._getWeeks = function (propsToUse) {
        var navigatedDate = propsToUse.navigatedDate, selectedDate = propsToUse.selectedDate, dateRangeType = propsToUse.dateRangeType, firstDayOfWeek = propsToUse.firstDayOfWeek, today = propsToUse.today, minDate = propsToUse.minDate, maxDate = propsToUse.maxDate, showSixWeeksByDefault = propsToUse.showSixWeeksByDefault, workWeekDays = propsToUse.workWeekDays;
        var date = new Date(navigatedDate.getFullYear(), navigatedDate.getMonth(), 1);
        var todaysDate = today || new Date();
        var weeks = [];
        // Cycle the date backwards to get to the first day of the week.
        while (date.getDay() !== firstDayOfWeek) {
            date.setDate(date.getDate() - 1);
        }
        // a flag to indicate whether all days of the week are in the month
        var isAllDaysOfWeekOutOfMonth = false;
        // in work week view we want to select the whole week
        var selectedDateRangeType = dateRangeType === DateRangeType.WorkWeek ? DateRangeType.Week : dateRangeType;
        var selectedDates = getDateRangeArray(selectedDate, selectedDateRangeType, firstDayOfWeek, workWeekDays);
        if (dateRangeType !== DateRangeType.Day) {
            selectedDates = this._getBoundedDateRange(selectedDates, minDate, maxDate);
        }
        var shouldGetWeeks = true;
        for (var weekIndex = 0; shouldGetWeeks; weekIndex++) {
            var week = [];
            isAllDaysOfWeekOutOfMonth = true;
            for (var dayIndex = 0; dayIndex < DAYS_IN_WEEK; dayIndex++) {
                var originalDate = new Date(date.toString());
                var dayInfo = {
                    key: date.toString(),
                    date: date.getDate().toString(),
                    originalDate: originalDate,
                    isInMonth: date.getMonth() === navigatedDate.getMonth(),
                    isToday: compareDates(todaysDate, date),
                    isSelected: isInDateRangeArray(date, selectedDates),
                    onSelected: this._onSelectDate.bind(this, originalDate),
                    isInBounds: (minDate ? compareDatePart(minDate, date) < 1 : true) &&
                        (maxDate ? compareDatePart(date, maxDate) < 1 : true) &&
                        !this._getIsRestrictedDate(date)
                };
                week.push(dayInfo);
                if (dayInfo.isInMonth) {
                    isAllDaysOfWeekOutOfMonth = false;
                }
                date.setDate(date.getDate() + 1);
            }
            // We append the condition of the loop depending upon the showSixWeeksByDefault prop.
            shouldGetWeeks = showSixWeeksByDefault ? !isAllDaysOfWeekOutOfMonth || weekIndex <= 5 : !isAllDaysOfWeekOutOfMonth;
            if (shouldGetWeeks) {
                weeks.push(week);
            }
        }
        return weeks;
    };
    CalendarDay.prototype._getIsRestrictedDate = function (date) {
        var restrictedDates = this.props.restrictedDates;
        if (!restrictedDates) {
            return false;
        }
        var restrictedDate = find(restrictedDates, function (rd) {
            return compareDates(rd, date);
        });
        return restrictedDate ? true : false;
    };
    CalendarDay.prototype._getBoundedDateRange = function (dateRange, minDate, maxDate) {
        var boundedDateRange = dateRange.slice();
        if (minDate) {
            boundedDateRange = boundedDateRange.filter(function (date) { return compareDatePart(date, minDate) >= 0; });
        }
        if (maxDate) {
            boundedDateRange = boundedDateRange.filter(function (date) { return compareDatePart(date, maxDate) <= 0; });
        }
        return boundedDateRange;
    };
    /**
     * Returns the index of the last element in the array where the predicate is true, and -1
     * otherwise
     * @param items Array of items to be iterated over using the predicate
     * @param predicate find calls predicate once for each element of the array, in descending
     * order, until it finds one where predicate returns true if such an element is found.
     */
    CalendarDay.prototype._findLastIndex = function (items, predicate) {
        for (var i = items.length - 1; i >= 0; i--) {
            var item = items[i];
            if (predicate(item)) {
                return i;
            }
        }
        return -1;
    };
    return CalendarDay;
}(BaseComponent));
export { CalendarDay };
//# sourceMappingURL=CalendarDay.js.map