import Random from '../../primitives/Random.js';
import * as Utils from '../../primitives/utils.js';
import { WalletError } from '../WalletError.js';
import { InvokableWalletBase } from './InvokableWalletBase.js';
/**
 * Facilitates wallet operations over cross-document messaging.
 */
export default class ReactNativeWebView extends InvokableWalletBase {
    domain;
    constructor(domain = '*') {
        super();
        if (typeof globalThis.window !== 'object') {
            throw new TypeError('The XDM substrate requires a global window object.');
        }
        if (!globalThis.window.hasOwnProperty("ReactNativeWebView")) {
            throw new Error('The window object does not have a ReactNativeWebView property.');
        }
        if (typeof globalThis.window.ReactNativeWebView.postMessage !== 'function') {
            throw new TypeError('The window.ReactNativeWebView property does not seem to support postMessage calls.');
        }
        this.domain = domain;
    }
    async invoke(call, args) {
        return await new Promise((resolve, reject) => {
            const id = Utils.toBase64(Random(12));
            const listener = (e) => {
                const data = JSON.parse(e.data);
                if (data.type !== 'CWI' ||
                    data.id !== id ||
                    data.isInvocation === true) {
                    return;
                }
                if (typeof globalThis.window.removeEventListener === 'function') {
                    globalThis.window.removeEventListener('message', listener);
                }
                if (data.status === 'error') {
                    const err = new WalletError(data.description, data.code);
                    reject(err);
                }
                else {
                    resolve(data.result);
                }
            };
            globalThis.window.addEventListener('message', listener);
            globalThis.window.ReactNativeWebView.postMessage(JSON.stringify({
                type: 'CWI',
                isInvocation: true,
                id,
                call,
                args
            }));
        });
    }
}
//# sourceMappingURL=ReactNativeWebView.js.map