"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.AdyenPaymentOption = void 0;
require("@adyen/adyen-web/styles/adyen.css");
require("./Adyen.global.scss");
const auto_1 = require("@adyen/adyen-web/auto");
const contexts_1 = require("../../../../contexts/index.js");
const react_1 = __importStar(require("react"));
const Headline_1 = __importDefault(require("../../../generic/Headline"));
let paymentResolveFunction;
let paymentPromise;
exports.AdyenPaymentOption = (0, react_1.forwardRef)(function ForwardedAdyenPaymentOption(props, ref) {
    var _a, _b;
    const adyenTarget = (0, react_1.useRef)(null);
    const basketContext = (0, react_1.useContext)(contexts_1.BasketContext);
    const [adyenDropin, setAdyenDropin] = (0, react_1.useState)(null);
    const adyenCheckoutResponse = (_b = (_a = basketContext.reservationData) === null || _a === void 0 ? void 0 : _a.payment) === null || _b === void 0 ? void 0 : _b.adyen;
    (0, react_1.useImperativeHandle)(ref, () => ({
        submitPayment() {
            return __awaiter(this, void 0, void 0, function* () {
                return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
                    if (adyenDropin) {
                        adyenDropin.submit();
                        // Adyen's types are weird.
                        const response = (yield paymentPromise);
                        if (response && response.resultCode !== 'Authorised') {
                            return resolve({
                                success: false,
                                message: 'Payment failed to authorize',
                                data: { sessionData: response.sessionData, sessionResponse: response.sessionResult },
                            });
                        }
                        resolve({ success: true, message: 'Payment successful' });
                    }
                }));
            });
        },
    }));
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        let adyenCheckoutObj;
        (() => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d;
            if (!adyenCheckoutResponse || !adyenTarget.current || cancelled || !(adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.sessionId) || !(adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.sessionData)) {
                return;
            }
            // Sometimes the useEffect cancel isn't called, so if we're here with an existing adyen dropin, we should unmount it.
            if (adyenDropin) {
                adyenDropin.unmount();
            }
            paymentPromise = new Promise((resolve) => {
                paymentResolveFunction = resolve;
            });
            adyenCheckoutObj = yield (0, auto_1.AdyenCheckout)({
                session: {
                    id: (_a = adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.sessionId) !== null && _a !== void 0 ? _a : '',
                    sessionData: adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.sessionData,
                },
                environment: adyenCheckoutResponse.isLive ? 'live' : 'test',
                amount: {
                    currency: (_b = adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.currency) !== null && _b !== void 0 ? _b : '',
                    value: parseFloat((_c = adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.amount) !== null && _c !== void 0 ? _c : '0') * 100,
                },
                clientKey: (_d = adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.clientKey) !== null && _d !== void 0 ? _d : '',
                countryCode: adyenCheckoutResponse === null || adyenCheckoutResponse === void 0 ? void 0 : adyenCheckoutResponse.countryCode,
                onPaymentCompleted: (result) => {
                    paymentResolveFunction(result);
                },
                onPaymentFailed: (result, component) => {
                    component === null || component === void 0 ? void 0 : component.setStatus('error', { message: 'Payment failed to process' });
                    paymentResolveFunction(result);
                },
                showPayButton: false,
            });
            if (adyenTarget.current) {
                const dropin = new auto_1.Dropin(adyenCheckoutObj);
                dropin.mount(adyenTarget.current);
                setAdyenDropin(dropin);
            }
        }))();
        return () => {
            cancelled = true;
            if (adyenDropin) {
                adyenDropin.unmount();
            }
        };
    }, [adyenTarget, adyenCheckoutResponse]);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: "u-marg-bottom--heavy" },
            react_1.default.createElement(Headline_1.default, { bold: true }, "Choose your payment method")),
        react_1.default.createElement("div", { ref: adyenTarget, id: "dropin-container" })));
});
//# sourceMappingURL=AdyenPaymentOption.js.map