"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.default = FindReservationResults;
const contexts_1 = require("../../contexts/index.js");
const hooks_1 = require("../../hooks/index.js");
const core_1 = require("@roomstay/core");
const dayjs_1 = __importDefault(require("dayjs"));
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const react_router_dom_1 = require("react-router-dom");
const Translation_1 = require("translations/Translation");
const AutoAutoHeight_1 = __importDefault(require("../../animations/AutoAutoHeight"));
const BookingAPI_1 = __importDefault(require("../../api/BookingAPI"));
const Alert_1 = __importStar(require("../../components/generic/Alert"));
const BackButton_1 = __importDefault(require("../../components/generic/BackButton"));
const Currency_1 = __importDefault(require("../../components/generic/Currency"));
const Headline_1 = __importDefault(require("../../components/generic/Headline"));
const HtmlContentViewer_1 = require("../../components/generic/HtmlContentViewer");
const Icon_1 = require("../../components/generic/Icon/Icon");
const LineBreak_1 = __importDefault(require("../../components/generic/LineBreak"));
const LargeLoader_1 = __importDefault(require("../../components/generic/loader/LargeLoader"));
const PageTitle_1 = require("../../components/generic/PageTitle");
const TaxInclusionNotice_1 = require("../../components/generic/TaxInclusionNotice/TaxInclusionNotice");
const Text_1 = __importStar(require("../../components/generic/Text"));
const CommonAddonSummary_1 = require("../../components/steps/common/CommonAddonSummary/CommonAddonSummary");
const ItemisedFeesSummary_1 = require("../../components/steps/common/ItemisedFeesSummary/ItemisedFeesSummary");
const events_1 = require("../../events");
const ReservationRow_1 = __importDefault(require("./ReservationRow"));
const Color_1 = require("../../util/Color");
const TextAlignment_1 = require("../../util/TextAlignment");
function FindReservationResults() {
    var _a, _b;
    const params = (0, react_router_dom_1.useParams)();
    const navigate = (0, react_router_dom_1.useNavigate)();
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const ccx = (0, react_1.useContext)(contexts_1.CompanyContext);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [bookingInformation, setBookingInformation] = (0, react_1.useState)(null);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [cancellationMessage, setCancellationMessage] = (0, react_1.useState)('');
    const [cancellationTrigger, setCancellationTrigger] = (0, react_1.useState)(0);
    const [data, setData] = (0, react_1.useState)(null);
    const [itemisedFees, setItemisedFees] = (0, react_1.useState)([]);
    const pushHistoryOnClick = () => {
        navigate('../');
    };
    /**
     * Determines whether addon night count should be dismissed.
     * This is true when the booking is not from Roomstay, indicated by:
     * - the itinerary number not starting with 'RS', and
     * - the hotel not preferring provider booking IDs.
     */
    const dismissAddonNightCount = !((_a = bookingInformation === null || bookingInformation === void 0 ? void 0 : bookingInformation.itineraryNumber) === null || _a === void 0 ? void 0 : _a.startsWith('RS')) && !(hotel === null || hotel === void 0 ? void 0 : hotel.preferProviderBookingId);
    (0, react_1.useEffect)(() => {
        let isCancelled = false;
        setIsLoading(true);
        const handleSuccess = (data) => {
            if (!isCancelled) {
                setBookingInformation(data);
                setIsLoading(false);
                setData(data);
            }
        };
        if (params === null || params === void 0 ? void 0 : params.ref) {
            BookingAPI_1.default.Reservation.findReservation(params.ref, params.email, hotel === null || hotel === void 0 ? void 0 : hotel.hotelID)
                .then((data) => {
                if (data.hotelFrontendId && data.hotelFrontendId !== (hotel === null || hotel === void 0 ? void 0 : hotel.hotelID)) {
                    // User has searched for a booking that belongs to a different hotel (but within the same company).
                    // Let's redirect the user to the correct hotel.
                    ccx.getHotel(data.hotelFrontendId)
                        .then((hotel) => {
                        const findReservationUrl = `${hotel.hotelUrl}/${hotel.checkoutUrl}/#/find-reservation/${params.ref}/${params.email}`;
                        window.location.href = findReservationUrl;
                    })
                        .catch((error) => {
                        console.error(`Failed to find hotel: ${error}. Continuing with current hotel.`);
                        handleSuccess(data);
                    });
                }
                else {
                    handleSuccess(data);
                }
            })
                .catch(() => {
                navigate('/find-reservation');
            });
        }
        else {
            navigate('/find-reservation');
        }
        return () => {
            isCancelled = true;
        };
    }, [cancellationTrigger]);
    (0, react_1.useEffect)(() => {
        setItemisedFees((bookingInformation === null || bookingInformation === void 0 ? void 0 : bookingInformation.feesSummary) || []);
    }, [bookingInformation]);
    const addons = [];
    const comments = [];
    const total = (0, react_1.useCallback)(() => {
        if (bookingInformation === null || bookingInformation === void 0 ? void 0 : bookingInformation.reservations) {
            return core_1.TotalCalculator.calculateTotalForReservation(bookingInformation, dismissAddonNightCount);
        }
        return 0;
    }, [bookingInformation, dismissAddonNightCount]);
    const { raise } = (0, hooks_1.useEvent)();
    (0, react_1.useEffect)(() => {
        var _a, _b;
        if (!data)
            return;
        const reservations = (_b = (_a = data.reservations) === null || _a === void 0 ? void 0 : _a.map((obj) => {
            const nightKeys = Object.keys(obj.nights);
            const dateFormat = 'YYYY-MM-DDTHH:mm:ss';
            return {
                reservationId: obj.reservationNumber,
                checkInTime: (0, dayjs_1.default)(nightKeys[0]).format(dateFormat),
                checkOutTime: (0, dayjs_1.default)(nightKeys[nightKeys.length - 1])
                    .add(1, 'day')
                    .format(dateFormat),
                totalPrice: obj.total.afterTax,
                priceCurrency: ccx.currentCurrency,
            };
        })) !== null && _b !== void 0 ? _b : [];
        const event = new events_1.FindReservationResultsViewEvent(reservations);
        raise(event);
    }, [data]);
    return (react_1.default.createElement("div", { className: "container u-pad--heavy-plus u-pad-left u-pad-right" },
        react_1.default.createElement(PageTitle_1.PageTitle, { step: "FindReservation" }),
        isLoading ? (react_1.default.createElement(LargeLoader_1.default, null)) : (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("div", { className: "u-marg-bottom" },
                react_1.default.createElement(BackButton_1.default, { onClick: pushHistoryOnClick })),
            react_1.default.createElement(Headline_1.default, { size: "extra-large" }, t(Translation_1.Translation.FindReservation.YourItinerary)),
            react_1.default.createElement(Headline_1.default, { color: Color_1.Color.DarkGrey },
                "#", bookingInformation === null || bookingInformation === void 0 ? void 0 :
                bookingInformation.itineraryNumber),
            react_1.default.createElement("div", { className: "row u-marg-top--heavy" },
                react_1.default.createElement(AutoAutoHeight_1.default, { open: !!cancellationMessage },
                    react_1.default.createElement(Alert_1.default, null, cancellationMessage)), (_b = bookingInformation === null || bookingInformation === void 0 ? void 0 : bookingInformation.reservations) === null || _b === void 0 ? void 0 :
                _b.map((obj, index) => {
                    if (obj.addons) {
                        const nights = Object.keys(obj.nights);
                        obj.addons.forEach((addon) => {
                            if (dismissAddonNightCount) {
                                addons.push(addon);
                            }
                            else {
                                addons.push(Object.assign(Object.assign({}, addon), { nights: nights.length }));
                            }
                        });
                    }
                    if (obj.comments && index === 0) {
                        obj.comments.map((comment) => {
                            comments.push(comment);
                        });
                    }
                    return (react_1.default.createElement("div", { className: "col-lg-6", key: obj.reservationNumber },
                        react_1.default.createElement(ReservationRow_1.default, { reservation: obj, key: obj.reservationNumber })));
                })),
            (hotel === null || hotel === void 0 ? void 0 : hotel.itineraryNote) && (react_1.default.createElement(Alert_1.default, { icon: Icon_1.IconType.Info, type: Alert_1.AlertType.Alert },
                react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, asDiv: true },
                    react_1.default.createElement(HtmlContentViewer_1.HtmlContentViewer, { content: hotel.itineraryNote })))),
            react_1.default.createElement(LineBreak_1.default, null),
            react_1.default.createElement(CommonAddonSummary_1.CommonAddonSummary, { addons: addons }),
            comments.length >= 1 && (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement("div", { className: "u-marg-bottom" },
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.Grey }, t(Translation_1.Translation.Step.Confirmation.Comments))),
                comments.map((comment, index) => (react_1.default.createElement(Text_1.default, { key: index, type: Text_1.TextType.Small }, comment))),
                react_1.default.createElement(LineBreak_1.default, null))),
            react_1.default.createElement(ItemisedFeesSummary_1.ItemisedFeesSummary, { fees: itemisedFees }),
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, align: TextAlignment_1.TextAlign.Right }, t(Translation_1.Translation.Misc.Total)),
            react_1.default.createElement(Headline_1.default, { bold: true, size: "large", align: TextAlignment_1.TextAlign.Right },
                react_1.default.createElement(Currency_1.default, null, total)),
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, align: TextAlignment_1.TextAlign.Right, color: Color_1.Color.DarkGrey },
                react_1.default.createElement(TaxInclusionNotice_1.TaxInclusionNotice, null))))));
}
//# sourceMappingURL=FindReservationResults.js.map