"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.webBluetooth = webBluetooth;
const APINotImplementedError_1 = require("../../../../exception/APINotImplementedError");
const sleep_1 = require("../../../../sleep");
function webBluetooth(window, opt) {
    const { navigator } = window;
    const bluetooth = {
        requestDevice: async (opt) => {
            // @ts-ignore
            if (navigator.bluetooth) {
                // show system UI on next tick to prevent possible
                // interference with triggering event propagation
                await (0, sleep_1.sleep)(window.setTimeout);
                try {
                    // @ts-ignore
                    const device = await navigator.bluetooth.requestDevice(opt);
                    return {
                        getServer: async () => {
                            const { gatt } = device;
                            if (gatt) {
                                try {
                                    return (await device.gatt.connect());
                                }
                                catch (err) {
                                    throw new Error(err.message);
                                }
                            }
                            else {
                                throw new Error('cannot find bluetooth device remote GATT server');
                            }
                        },
                    };
                }
                catch (err) {
                    const { message } = err;
                    if (message === 'User cancelled the requestDevice() chooser.') {
                        throw new Error('user cancelled chooser');
                    }
                    else if (message ===
                        "Failed to execute 'requestDevice' on 'Bluetooth': Either 'filters' should be present or 'acceptAllDevices' should be true, but not both.") {
                        throw new Error(`either 'filters' should be present or 'acceptAllDevices' should be true, but not both.`);
                    }
                    else {
                        throw err;
                    }
                }
            }
            else {
                throw new APINotImplementedError_1.APINotSupportedError('Bluetooth');
            }
        },
    };
    return bluetooth;
}
//# sourceMappingURL=bluetooth.js.map