"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DatePickerDayStatus = void 0;
exports.default = DatePickerDay;
const contexts_1 = require("../../../contexts/index.js");
const hooks_1 = require("../../../hooks/index.js");
const classnames_1 = __importDefault(require("classnames"));
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const Translation_1 = require("translations/Translation");
const AvailabilityAPI_1 = __importDefault(require("../../../api/AvailabilityAPI"));
const BookingAPI_1 = __importDefault(require("../../../api/BookingAPI"));
const Currency_1 = __importDefault(require("../Currency"));
const Icon_1 = __importStar(require("../Icon/Icon"));
const Text_1 = __importStar(require("../Text"));
const Tooltip_1 = __importDefault(require("../Tooltip/Tooltip"));
const useSignedInMember_1 = require("../../../hooks/useSignedInMember");
const Color_1 = require("../../../util/Color");
var DatePickerDayStatus;
(function (DatePickerDayStatus) {
    DatePickerDayStatus[DatePickerDayStatus["Inactive"] = 0] = "Inactive";
    DatePickerDayStatus["Selecting"] = "--selecting";
    DatePickerDayStatus["Loading"] = "--loading";
    DatePickerDayStatus["Selected"] = "--selected";
})(DatePickerDayStatus || (exports.DatePickerDayStatus = DatePickerDayStatus = {}));
function DatePickerDay(props) {
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const { memberNumber } = (0, useSignedInMember_1.useSignedInMember)();
    const { t } = (0, react_i18next_1.useTranslation)();
    const datePickerContext = (0, react_1.useContext)(contexts_1.DatePickerContext);
    const basketContext = (0, react_1.useContext)(contexts_1.BasketContext);
    const { checkAvailableNightStay } = (0, hooks_1.useCalendarNightStay)({ basketContext });
    const [price, setPrice] = (0, react_1.useState)();
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [isHovering, setIsHovering] = (0, react_1.useState)(false);
    const [isSelected, setIsSelected] = (0, react_1.useState)(false);
    const [isSelecting, setIsSelecting] = (0, react_1.useState)(false);
    const [isFirst, setIsFirst] = (0, react_1.useState)(false);
    const [isLast, setIsLast] = (0, react_1.useState)(false);
    const isCurrent = props.day && datePickerContext.today.isSame(props.day, 'date');
    const isPast = props.unix < datePickerContext.todayInUnix && !isCurrent;
    const { selectedBasketRow } = basketContext;
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        const adults = selectedBasketRow ? selectedBasketRow.getAdults() : 1;
        const children = selectedBasketRow ? selectedBasketRow.getChildren() : 0;
        const infants = selectedBasketRow ? selectedBasketRow.getInfants() : 0;
        const promoCode = selectedBasketRow ? selectedBasketRow.getPromoCode() : '';
        const roomCode = datePickerContext.roomCode;
        const rateCode = datePickerContext.rateCode;
        if (props.day && !isPast) {
            if (hotel) {
                setPrice(0);
                setIsLoading(true);
                // If dates are selected, the errors from the /availability call take precedence.
                const parseErrors = !datePickerContext.startDate;
                BookingAPI_1.default.Availability.getCheapestPriceForDay(props.day, adults, children, infants, promoCode, roomCode, rateCode, hotel.hotelID, memberNumber, parseErrors).then((foundedPrice) => {
                    if (!cancelled) {
                        if (foundedPrice) {
                            setPrice(foundedPrice.price);
                            if (datePickerContext.maxPrice < AvailabilityAPI_1.default.maxNightPrice) {
                                datePickerContext.setMaxPrice(AvailabilityAPI_1.default.maxNightPrice);
                            }
                        }
                        setIsLoading(false);
                    }
                });
            }
            else {
                datePickerContext.setMaxPrice(-1);
                setPrice(-1);
                setIsLoading(false);
            }
        }
        return () => {
            cancelled = true;
        };
    }, [
        props.day,
        selectedBasketRow === null || selectedBasketRow === void 0 ? void 0 : selectedBasketRow.getAdults(),
        selectedBasketRow === null || selectedBasketRow === void 0 ? void 0 : selectedBasketRow.getChildren(),
        selectedBasketRow === null || selectedBasketRow === void 0 ? void 0 : selectedBasketRow.getInfants(),
        selectedBasketRow === null || selectedBasketRow === void 0 ? void 0 : selectedBasketRow.getPromoCode(),
        datePickerContext.roomCode,
        memberNumber,
    ]);
    (0, react_1.useEffect)(() => {
        if (datePickerContext.hoveredMonth) {
            if (props.unix && datePickerContext.startDate.isBefore(props.day, 'date') && datePickerContext.hoveredMonth.isSameOrAfter(props.day, 'date')) {
                setIsSelecting(true);
                if (datePickerContext.hoveredMonth.isSame(props.day, 'date') || (datePickerContext.endDate && datePickerContext.endDate.isSame(props.day))) {
                    setIsLast(true);
                }
                else {
                    setIsLast(false);
                }
                return;
            }
        }
        setIsSelecting(false);
        setIsLast(false);
    }, [datePickerContext.hoveredMonth, props.day]);
    (0, react_1.useEffect)(() => {
        var _a, _b, _c;
        if (props.unix && datePickerContext.startDate) {
            if (((_a = datePickerContext.startDate) === null || _a === void 0 ? void 0 : _a.isSameOrBefore(props.day, 'date')) && ((_b = datePickerContext.endDate) === null || _b === void 0 ? void 0 : _b.isSameOrAfter(props.day, 'date'))) {
                setIsSelected(true);
                if ((_c = datePickerContext.endDate) === null || _c === void 0 ? void 0 : _c.isSame(props.day, 'date')) {
                    setIsLast(true);
                }
                return;
            }
            if (datePickerContext.startDate.isSame(props.day, 'date')) {
                setIsFirst(true);
                setIsSelected(true);
                return;
            }
        }
        setIsSelected(false);
        setIsFirst(false);
        setIsLast(false);
    }, [datePickerContext.startDate, datePickerContext.endDate, props.day]);
    const memo = (0, react_1.useMemo)(() => {
        var _a, _b, _c, _d;
        const onHoverIn = (e) => {
            datePickerContext.onHoverOver(props.day);
            setIsHovering(true);
        };
        const onHoverOut = (e) => {
            setIsHovering(false);
        };
        const isSelectable = () => {
            return !!(props.day && props.selectable && !isLoading && !isPast && (price || !hotel));
        };
        const onClick = (e) => {
            datePickerContext.onDayClicked(props.day);
        };
        const getHighlightForDay = () => {
            if (!props.day || !(hotel === null || hotel === void 0 ? void 0 : hotel.calendarHighlights))
                return null;
            const dayName = props.day.format('dddd').toLowerCase();
            return hotel.calendarHighlights.find((highlight) => highlight[dayName] && props.day.isBetween(highlight.startDate, highlight.endDate, 'day', '[]'));
        };
        const highlight = getHighlightForDay();
        const availableNightStay = checkAvailableNightStay({
            arrivalNightStay: datePickerContext === null || datePickerContext === void 0 ? void 0 : datePickerContext.arrivalNightStay,
            startDate: datePickerContext.startDate,
            dateToCheck: props.day,
        });
        const isDateInSelectedRange = () => {
            if (props.day && datePickerContext.startDate && datePickerContext.endDate) {
                if (props.day <= datePickerContext.endDate && props.day >= datePickerContext.startDate) {
                    return true;
                }
            }
            return false;
        };
        const isDateBeforeArrivalDate = props.day && datePickerContext.startDate && datePickerContext.startDate.isAfter(props.day);
        const isNightStayAvailable = () => {
            if (datePickerContext.endDate && datePickerContext.startDate) {
                //selected both Arrival/Departure date
                return datePickerContext.startDate.isAfter(props.day) || datePickerContext.endDate.isBefore(props.day);
            }
            else if (datePickerContext.startDate) {
                //selected Arrival date only
                return availableNightStay.available && !isDateBeforeArrivalDate;
            }
            else {
                //no selected date
                return true;
            }
        };
        // This is insane, needs to be re-worked
        const hovered = isHovering && isSelectable() && !isDateInSelectedRange() && ((_b = (_a = datePickerContext.hoveredMonth) === null || _a === void 0 ? void 0 : _a.isSame) === null || _b === void 0 ? void 0 : _b.call(_a, props.day, 'date'));
        const classes = (0, classnames_1.default)(`diji-calendar-${(_c = props.displayType) !== null && _c !== void 0 ? _c : 'month'}--item`, {
            '--selectable': isSelectable(),
            '--hovered': hovered,
            '--past': !isSelectable(),
            '--current': isCurrent,
            '--first': isFirst,
            '--last': isLast,
            '--loading': isLoading,
            '--selected': isSelected,
            '--selecting': isSelecting && !isSelected,
            '--night-stay-unavailable': !isNightStayAvailable(),
        });
        const events = {};
        if (!props.readOnly) {
            //Disable all event listeners
            events.onMouseEnter = onHoverIn;
            events.onMouseLeave = onHoverOut;
            events.onClick = onClick;
        }
        const getTooltipTitleSetting = () => {
            let titleTooltip = {
                BlockedDate: t(Translation_1.Translation.Step.Date.NightStayRequirement.BlockedDate),
                DateBeforeArrivalDate: t(Translation_1.Translation.Step.Date.NightStayRequirement.DateBeforeArrivalDate),
                ArrivalDate: '',
                BetweenArrivalDateMinDepartureDate: t(Translation_1.Translation.Step.Date.NightStayRequirement.BetweenArrivalDateMinDepartureDate),
                AvailableDate: '',
                DateInSelectedRange: '',
                DateAfterMaxDepartureDate: t(Translation_1.Translation.Step.Date.NightStayRequirement.DateAfterMaxDepartureDate),
            };
            if (datePickerContext === null || datePickerContext === void 0 ? void 0 : datePickerContext.endDate) {
                const ChangeArrivalDate = t(Translation_1.Translation.Step.Date.NightStayRequirement.ChangeArrivalDate);
                titleTooltip = {
                    BlockedDate: '',
                    DateBeforeArrivalDate: ChangeArrivalDate,
                    ArrivalDate: t(Translation_1.Translation.Step.Date.NightStayRequirement.PickAgain),
                    BetweenArrivalDateMinDepartureDate: ChangeArrivalDate,
                    AvailableDate: ChangeArrivalDate,
                    DateInSelectedRange: ChangeArrivalDate,
                    DateAfterMaxDepartureDate: ChangeArrivalDate,
                };
            }
            return titleTooltip;
        };
        const getTooltipTitle = () => {
            var _a, _b, _c, _d, _e;
            const setting = getTooltipTitleSetting();
            if (!price) {
                //Blocked dates
                return setting.BlockedDate;
            }
            if (availableNightStay.minDate) {
                if ((props === null || props === void 0 ? void 0 : props.day.isAfter(datePickerContext.startDate)) && ((_a = availableNightStay.minDate) === null || _a === void 0 ? void 0 : _a.isAfter(props.day))) {
                    //Dates between Arrival date and Min Departure Date
                    return setting.BetweenArrivalDateMinDepartureDate;
                }
            }
            if (availableNightStay.available) {
                //Available dates
                if (isDateBeforeArrivalDate) {
                    //Date before Arrival date (case when hotel have no min./max. nights stay)
                    return setting.DateBeforeArrivalDate;
                }
                return setting.AvailableDate;
            }
            else {
                //unavailable dates
                if ((_b = datePickerContext.startDate) === null || _b === void 0 ? void 0 : _b.isAfter(props.day)) {
                    //Date before Arrival date
                    return setting.DateBeforeArrivalDate;
                }
                if ((_c = datePickerContext.startDate) === null || _c === void 0 ? void 0 : _c.isSame(props.day)) {
                    //Date is Arrival date
                    return setting.ArrivalDate;
                }
                if (availableNightStay.minDate) {
                    if ((_d = availableNightStay.minDate) === null || _d === void 0 ? void 0 : _d.isAfter(props.day)) {
                        //Dates before Min Departure Date
                        return setting.BetweenArrivalDateMinDepartureDate;
                    }
                }
                if (availableNightStay.maxDate) {
                    if ((_e = availableNightStay.maxDate) === null || _e === void 0 ? void 0 : _e.isBefore(props.day)) {
                        // //Dates after Max Departure Date
                        return setting.DateAfterMaxDepartureDate;
                    }
                }
                return null;
            }
        };
        const priceBlock = props.day && props.selectable && !isPast && (price || (isLoading && !price)) && price >= 0 ? (react_1.default.createElement("div", { className: `diji-calendar-${(_d = props.displayType) !== null && _d !== void 0 ? _d : 'month'}--item-cost` }, isLoading ? (react_1.default.createElement("div", { className: "u-inline-flex a-spin" },
            react_1.default.createElement(Icon_1.default, { color: Color_1.Color.Accent, icon: Icon_1.IconType.Spinner, size: "14px" }))) : (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label },
            react_1.default.createElement(Currency_1.default, { shortenThousandsAfter: 6, removeCurrencyAfterChar: 5, forceHideDecimals: true, disableLocalization: true }, price))))) : (react_1.default.createElement(react_1.default.Fragment, null));
        if (props.displayType === 'week') {
            let height = 0;
            const range = (price / AvailabilityAPI_1.default.maxNightPrice) * 100;
            if (isSelectable()) {
                if (range < 10) {
                    height = 10;
                }
                else if (range > 90) {
                    height = 90;
                }
                else {
                    height = range;
                }
            }
            else {
                if (!isLoading) {
                    height = 95;
                }
            }
            return (react_1.default.createElement("div", Object.assign({ className: classes }, events),
                props.text === '1' && react_1.default.createElement("div", { className: "diji-calendar-week--month-indicator" }, props.day.format('MMMM')),
                react_1.default.createElement("div", { className: "diji-calendar-week--day-label" }, props.day.format('dd')),
                react_1.default.createElement("div", { className: "diji-calendar-week--day-digit" },
                    react_1.default.createElement(Text_1.default, null, props.text)),
                react_1.default.createElement("div", { className: "diji-calendar-week--price-indicator" },
                    react_1.default.createElement("div", { className: "diji-calendar-week--price-indicator-block", style: { maxHeight: `${height}%` } })),
                priceBlock));
        }
        else {
            if (datePickerContext.startDate) {
                const tooltipTitle = getTooltipTitle();
                if (tooltipTitle) {
                    return (react_1.default.createElement("div", Object.assign({ className: classes }, events),
                        react_1.default.createElement(Tooltip_1.default, { title: tooltipTitle, usePortal: true, open: hovered, preventMouseInteraction: true },
                            react_1.default.createElement(Text_1.default, null, props.text),
                            priceBlock),
                        highlight && react_1.default.createElement("div", { className: "diji-calendar-month--item-highlight", style: { backgroundColor: highlight.color } })));
                }
            }
            return (react_1.default.createElement("div", Object.assign({ className: classes }, events),
                react_1.default.createElement("div", null,
                    react_1.default.createElement(Text_1.default, null, props.text),
                    priceBlock),
                highlight && react_1.default.createElement("div", { className: "diji-calendar-month--item-highlight", style: { backgroundColor: highlight.color } })));
        }
    }, [
        isFirst,
        isLast,
        isSelecting,
        isSelected,
        isHovering,
        isLoading,
        props.unix,
        datePickerContext.hoveredMonth,
        datePickerContext.startDate,
        datePickerContext.endDate,
        basketContext,
        datePickerContext.maxPrice,
        hotel,
        datePickerContext === null || datePickerContext === void 0 ? void 0 : datePickerContext.arrivalNightStay,
        datePickerContext === null || datePickerContext === void 0 ? void 0 : datePickerContext.nightStayValidation,
        props.day,
        props.readOnly,
    ]);
    return memo;
}
//# sourceMappingURL=DatePickerDay.js.map