"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
var context_1 = require("../context");
var dom_util_1 = require("../dom-util");
var framepay_error_1 = __importDefault(require("../framepay-error"));
var get_framepay_api_1 = __importDefault(require("../get-framepay-api"));
var Provider = /** @class */ (function (_super) {
    __extends(Provider, _super);
    function Provider() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            api: (0, get_framepay_api_1.default)(),
            error: null,
            ready: false,
        };
        return _this;
    }
    Provider.prototype.componentDidMount = function () {
        var _this = this;
        if (this.props.injectScript) {
            (0, dom_util_1.injectScript)({
                onError: function () { return _this.onApiError(); },
                onReady: function () { return _this.onApiReady(); },
            });
        }
    };
    Provider.prototype.onApiError = function () {
        return this.setState({
            error: framepay_error_1.default.codes.remoteScriptError,
            ready: false,
        }, function () {
            var error = (0, framepay_error_1.default)({
                code: framepay_error_1.default.codes.remoteScriptError,
            });
            throw error;
        });
    };
    Provider.prototype.onApiReady = function () {
        return __awaiter(this, void 0, void 0, function () {
            var api, _a, children, settings;
            var _this = this;
            return __generator(this, function (_b) {
                api = (0, get_framepay_api_1.default)();
                try {
                    _a = this.props, children = _a.children, settings = __rest(_a, ["children"]);
                    api.initialize(settings);
                    api.on('ready', function () {
                        _this.setState({ ready: true, api: api, error: null });
                        // call onReady callback
                        if (_this.props.onReady) {
                            _this.props.onReady();
                        }
                    });
                    api.on('error', function (error) {
                        var _a;
                        _this.setState({
                            api: api,
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            error: (_a = error === null || error === void 0 ? void 0 : error.code) !== null && _a !== void 0 ? _a : 0,
                        });
                        // call error callback
                        if (_this.props.onError) {
                            _this.props.onError(error);
                        }
                    });
                    api.on('token-ready', function (token) {
                        if (_this.props.onTokenReady) {
                            _this.props.onTokenReady(token);
                        }
                    });
                }
                catch (e) {
                    return [2 /*return*/, this.setState({
                            error: framepay_error_1.default.codes.initializeError,
                            ready: false,
                        }, function () {
                            throw (0, framepay_error_1.default)({
                                code: framepay_error_1.default.codes.initializeError,
                                details: 'Api initialize error',
                                trace: e,
                            });
                        })];
                }
                return [2 /*return*/];
            });
        });
    };
    Provider.prototype.render = function () {
        return (React.createElement(context_1.ContextProvider, { value: this.state }, this.props.children));
    };
    Provider.defaultProps = {
        injectScript: true,
        onError: function () { return ({}); },
        onReady: function () { return ({}); },
        onTokenReady: function () { return ({}); },
    };
    return Provider;
}(React.Component));
exports.default = Provider;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJvdmlkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvbGliL2NvbXBvbmVudHMvcHJvdmlkZXIudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBQSwyQ0FBK0I7QUFDL0Isc0NBQTZDO0FBQzdDLHdDQUEyQztBQUMzQyxxRUFBOEM7QUFDOUMseUVBQWlEO0FBS2pEO0lBQXNDLDRCQUdyQztJQUhEOztRQVdhLFdBQUssR0FBb0I7WUFDOUIsR0FBRyxFQUFFLElBQUEsMEJBQWMsR0FBRTtZQUNyQixLQUFLLEVBQUUsSUFBSTtZQUNYLEtBQUssRUFBRSxLQUFLO1NBQ2YsQ0FBQzs7SUFp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