"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderRecentSearchesEngineElement = exports.RecentSearchesEngineElement = void 0;
const contexts_1 = require("../../contexts/index.js");
const dayjs_1 = __importDefault(require("dayjs"));
const react_1 = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const react_i18next_1 = require("react-i18next");
const BEButton_1 = __importDefault(require("../../components/generic/BEButton"));
const Icon_1 = require("../../components/generic/Icon/Icon");
const RecentSearchesCard_1 = __importDefault(require("../../components/generic/RecentSearchesCard"));
const Text_1 = __importStar(require("../../components/generic/Text"));
const RoomstayThemeEngine_1 = __importDefault(require("../../providers/RoomstayThemeEngine"));
const SessionProvider_1 = __importDefault(require("../../providers/storage/SessionProvider"));
const Translation_1 = require("../../translations/Translation");
const Color_1 = require("../../util/Color");
const GetStepRoom_1 = __importDefault(require("../../util/GetStepRoom"));
const ScreenSize_1 = __importDefault(require("../../util/ScreenSize"));
const RecentSearchesEngineElement = ({ engine }) => {
    const { t } = (0, react_i18next_1.useTranslation)();
    const [currentSessions, setCurrentSessions] = (0, react_1.useState)([]);
    const beContext = (0, react_1.useContext)(contexts_1.BookingEngineContext);
    const hotel = (0, react_1.useMemo)(() => {
        var _a;
        const config = engine.getConfig();
        const selectedHotel = (_a = config === null || config === void 0 ? void 0 : config.company) === null || _a === void 0 ? void 0 : _a.selectedHotel;
        if (selectedHotel) {
            return config.company.hotels.find((hotel) => hotel.hotelID === selectedHotel || hotel.hotelID === (selectedHotel === null || selectedHotel === void 0 ? void 0 : selectedHotel.hotelID));
        }
    }, [engine]);
    (0, react_1.useEffect)(() => {
        resetSessions();
    }, []);
    (0, react_1.useEffect)(() => {
        if (hotel) {
            RoomstayThemeEngine_1.default.changeTheme(hotel === null || hotel === void 0 ? void 0 : hotel.colors);
        }
    }, [hotel]);
    const resetSessions = () => {
        engine
            .getSessionProvider()
            .getAllSessions()
            .then((sessions) => {
            const sessionsToUse = [];
            sessions.forEach((session) => {
                var _a;
                if (!hotel || ((hotel === null || hotel === void 0 ? void 0 : hotel.hotelID) === session.hotelID && ((_a = session.basketRows) === null || _a === void 0 ? void 0 : _a.length) > 0)) {
                    let hasValidRow = false;
                    session.basketRows.forEach((basket) => {
                        if (basket.isValid() && basket.getStartDate().isAfter((0, dayjs_1.default)())) {
                            hasValidRow = true;
                        }
                    });
                    if (hasValidRow) {
                        sessionsToUse.push(session);
                    }
                }
            });
            sessionsToUse.reverse();
            setCurrentSessions(sessionsToUse);
        });
    };
    const smallBlurb = (react_1.default.createElement(Text_1.default, { color: Color_1.Color.White, type: Text_1.TextType.Small }, t(Translation_1.Translation.RecentSearch.SubTagLine)));
    const onRemoveCard = (session) => __awaiter(void 0, void 0, void 0, function* () {
        const provider = new SessionProvider_1.default();
        yield provider.initialize(session.id);
        provider.deleteSession();
        resetSessions();
    });
    const redirectToCheckout = () => {
        window.open(hotel === null || hotel === void 0 ? void 0 : hotel.checkoutUrl);
    };
    return currentSessions.length ? (react_1.default.createElement("div", { style: { backgroundColor: Color_1.Color.Navy } },
        react_1.default.createElement("div", { className: "container" },
            react_1.default.createElement("div", { className: "u-pad-top-bottom--heavy" },
                react_1.default.createElement("div", { className: "u-marg-bottom" },
                    react_1.default.createElement(Text_1.default, { color: Color_1.Color.White, bold: true }, t(Translation_1.Translation.RecentSearch.RecentSearches)),
                    beContext.screenSize <= ScreenSize_1.default.Medium && smallBlurb),
                react_1.default.createElement("div", { className: "row u-marg-bottom" }, !!(currentSessions === null || currentSessions === void 0 ? void 0 : currentSessions.length) &&
                    currentSessions.slice(0, 2).map((session) => {
                        let validRow = undefined;
                        for (const row of session.basketRows) {
                            if (row.isValid()) {
                                validRow = row;
                                break;
                            }
                        }
                        const removeCard = () => {
                            onRemoveCard(session);
                        };
                        const onViewRates = () => __awaiter(void 0, void 0, void 0, function* () {
                            const manager = new SessionProvider_1.default();
                            yield manager.initialize(session.id);
                            manager
                                .updateSession({
                                step: (0, GetStepRoom_1.default)().getName(),
                            })
                                .then(() => {
                                var _a;
                                window.open(`${(_a = hotel === null || hotel === void 0 ? void 0 : hotel.checkoutUrl) !== null && _a !== void 0 ? _a : '/checkout/'}#${(0, GetStepRoom_1.default)().getStepUrl()}?session=${session.id}`, '_self');
                            });
                        });
                        return (react_1.default.createElement("div", { key: validRow === null || validRow === void 0 ? void 0 : validRow.getID(), className: "col-lg-6" },
                            react_1.default.createElement(RecentSearchesCard_1.default, { basketRow: validRow, onRemove: removeCard, onViewRatesClicked: onViewRates })));
                    })),
                react_1.default.createElement("div", { className: "u-flex u-flex-align-center flex-column flex-md-row justify-align-content-md-center" },
                    beContext.screenSize > ScreenSize_1.default.Medium && smallBlurb,
                    react_1.default.createElement(BEButton_1.default, { icon: Icon_1.IconType.ArrowRight, iconPosition: "right", primary: true, filled: true, onClick: redirectToCheckout }, t(Translation_1.Translation.RecentSearch.SeeAllRooms, {
                        hotelName: hotel === null || hotel === void 0 ? void 0 : hotel.name,
                    }))))))) : (react_1.default.createElement(react_1.default.Fragment, null));
};
exports.RecentSearchesEngineElement = RecentSearchesEngineElement;
const renderRecentSearchesEngineElement = (container, engine) => {
    (0, react_dom_1.render)(react_1.default.createElement(contexts_1.BookingEngineContextWrapper, { engine: engine },
        react_1.default.createElement(exports.RecentSearchesEngineElement, { engine: engine })), container);
};
exports.renderRecentSearchesEngineElement = renderRecentSearchesEngineElement;
//# sourceMappingURL=RecentSearchesEngineElement.js.map