"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.withNextStepConfirmationDialog = exports.useNextStepAction = void 0;
const contexts_1 = require("../contexts/index.js");
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const BEButton_1 = __importDefault(require("../components/generic/BEButton"));
const SimpleModal_1 = __importStar(require("../components/generic/modal/SimpleModal"));
const Text_1 = __importDefault(require("../components/generic/Text"));
const RoomRateAvailabilityListFromApi_1 = require("./RoomRateAvailabilityListFromApi");
const Translation_1 = require("../translations/Translation");
const useNextStepAction = () => {
    const { getAllValidRows, updateBasketRow } = (0, react_1.useContext)(contexts_1.BasketContext);
    const { getRoomsByBasketRow } = (0, RoomRateAvailabilityListFromApi_1.useRoomRateAvailabilityListFromApi)();
    const validateRoomRateMatchedPrice = (basketRow) => __awaiter(void 0, void 0, void 0, function* () {
        var _a;
        const roomRate = basketRow.getRate();
        const rooms = yield getRoomsByBasketRow(basketRow);
        const latestRate = (roomRate === null || roomRate === void 0 ? void 0 : roomRate.code) ? (_a = rooms.find(({ code }) => { var _a; return code === ((_a = roomRate === null || roomRate === void 0 ? void 0 : roomRate.getRoom()) === null || _a === void 0 ? void 0 : _a.code); })) === null || _a === void 0 ? void 0 : _a.getRate(roomRate === null || roomRate === void 0 ? void 0 : roomRate.code) : null;
        return {
            matched: (roomRate === null || roomRate === void 0 ? void 0 : roomRate.getAveragePrice(true)) === (latestRate === null || latestRate === void 0 ? void 0 : latestRate.getAveragePrice(true)),
            latestRate: latestRate !== null && latestRate !== void 0 ? latestRate : null,
        };
    });
    const getBasketRowUnMatchedPrice = () => __awaiter(void 0, void 0, void 0, function* () {
        const allValidRows = getAllValidRows();
        const invalidRows = [];
        for (const basketRow of allValidRows) {
            const validation = yield validateRoomRateMatchedPrice(basketRow);
            if (validation.matched === false) {
                invalidRows.push({
                    basketRow: basketRow,
                    validation: validation,
                });
            }
        }
        return invalidRows;
    });
    const syncBasketRowUnMatchedPrice = () => __awaiter(void 0, void 0, void 0, function* () {
        const allValidRows = getAllValidRows();
        for (const basketRow of allValidRows) {
            const matchedPrice = yield validateRoomRateMatchedPrice(basketRow);
            if (matchedPrice.matched === false) {
                basketRow.setRate(matchedPrice === null || matchedPrice === void 0 ? void 0 : matchedPrice.latestRate);
                basketRow.setPreGuestsState();
                updateBasketRow(basketRow);
            }
        }
    });
    return { getBasketRowUnMatchedPrice, syncBasketRowUnMatchedPrice };
};
exports.useNextStepAction = useNextStepAction;
//HOC
const withNextStepConfirmationDialog = (WrappedComponent) => {
    return function WithConfirmationDialog(props) {
        const { t } = (0, react_i18next_1.useTranslation)();
        const { updateBasketRow } = (0, react_1.useContext)(contexts_1.BasketContext);
        const { getBasketRowUnMatchedPrice, syncBasketRowUnMatchedPrice } = (0, exports.useNextStepAction)();
        const [showConfirmationDialog, setShowConfirmationDialog] = (0, react_1.useState)(false);
        const [hasUnavailableBasket, setHasUnavailableBasket] = (0, react_1.useState)(false);
        const onClickHandler = (event) => __awaiter(this, void 0, void 0, function* () {
            var _a;
            const basketRowUnMatchedPrice = yield getBasketRowUnMatchedPrice();
            if (basketRowUnMatchedPrice.length === 0) {
                //Pre-validation passed
                (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props);
            }
            else {
                //Pre-validation failed
                //Show dymanic alert here
                setHasUnavailableBasket(basketRowUnMatchedPrice.some(({ validation }) => !validation.latestRate));
                setShowConfirmationDialog(true);
                event.stopPropagation();
                event.preventDefault();
            }
        });
        const onDiscardHandler = () => __awaiter(this, void 0, void 0, function* () {
            var _a;
            setShowConfirmationDialog(false);
            const basketRowUnMatchedPrice = yield getBasketRowUnMatchedPrice();
            for (const { basketRow } of basketRowUnMatchedPrice) {
                basketRow.discardGuestsState();
                updateBasketRow(basketRow, true);
            }
            (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props);
        });
        const onSyncChangesHandler = () => __awaiter(this, void 0, void 0, function* () {
            var _a;
            setShowConfirmationDialog(false);
            yield syncBasketRowUnMatchedPrice();
            (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props);
        });
        const openCloseHandler = () => {
            setShowConfirmationDialog(false);
        };
        return (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(WrappedComponent, Object.assign({}, props, { onClick: onClickHandler })),
            react_1.default.createElement(SimpleModal_1.default, { open: showConfirmationDialog, onClose: openCloseHandler, alignCenter: true, size: SimpleModal_1.SimpleModalSize.ExtraSmall },
                react_1.default.createElement("div", { className: "u-pad--heavy inactivity-window" },
                    react_1.default.createElement("div", { className: "u-marg-bottom--heavy" }, hasUnavailableBasket ? (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement(Text_1.default, null, t(Translation_1.Translation.Step.Room.UnMatchedBasketRowPrice.ConfirmUpdateAndClearAlert)),
                        react_1.default.createElement(Text_1.default, null, t(Translation_1.Translation.Step.Room.UnMatchedBasketRowPrice.ConfirmUpdateAndClearAlert2)))) : (react_1.default.createElement(Text_1.default, null, t(Translation_1.Translation.Step.Room.UnMatchedBasketRowPrice.ConfirmKeepChangesAlert)))),
                    react_1.default.createElement("div", { className: "u-flex" },
                        react_1.default.createElement("div", { className: "u-marg-right--light u-w-100" },
                            react_1.default.createElement(BEButton_1.default, { wide: true, onClick: onDiscardHandler }, t(Translation_1.Translation.Misc.No))),
                        react_1.default.createElement("div", { className: "u-w-100" },
                            react_1.default.createElement(BEButton_1.default, { wide: true, filled: true, primary: true, onClick: onSyncChangesHandler }, hasUnavailableBasket ? t(Translation_1.Translation.Step.Room.UnMatchedBasketRowPrice.Continue) : t(Translation_1.Translation.Step.Room.UnMatchedBasketRowPrice.YesUpdate))))))));
    };
};
exports.withNextStepConfirmationDialog = withNextStepConfirmationDialog;
//# sourceMappingURL=useNextStepAction.js.map