"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 (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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;
    return g = { next: verb(0), "throw": verb(1), "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 (_) 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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var bytebuffer_1 = require("bytebuffer");
var eventemitter2_1 = require("eventemitter2");
var p_queue_1 = require("p-queue");
var device_1 = require("./device");
var SEGMENT_SIZE = 63;
var WebUSBDevice = /** @class */ (function (_super) {
    __extends(WebUSBDevice, _super);
    function WebUSBDevice(config) {
        var _this = _super.call(this) || this;
        _this.interface = 'StandardWebUSB';
        _this.usbDevice = config.usbDevice;
        _this.events = config.events || new eventemitter2_1.default.EventEmitter2();
        _this.queue = new p_queue_1.default({ concurrency: 1 });
        return _this;
    }
    WebUSBDevice.requestPair = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, window.navigator.usb.requestDevice({ filters: [{ vendorId: 0x2b24 }] })];
            });
        });
    };
    Object.defineProperty(WebUSBDevice.prototype, "isInitialized", {
        get: function () {
            return this.usbDevice.opened;
        },
        enumerable: true,
        configurable: true
    });
    WebUSBDevice.prototype.initialize = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.isInitialized) return [3 /*break*/, 5];
                        return [4 /*yield*/, this.usbDevice.open()];
                    case 1:
                        _a.sent();
                        if (!(this.usbDevice.configuration === null)) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.usbDevice.selectConfiguration(1)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [4 /*yield*/, this.usbDevice.claimInterface(0)];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    WebUSBDevice.prototype.disconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.usbDevice.opened)
                            return [2 /*return*/];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        // If the device is disconnected, this will fail and throw, which is fine.
                        return [4 /*yield*/, this.usbDevice.releaseInterface(0)];
                    case 2:
                        // If the device is disconnected, this will fail and throw, which is fine.
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        e_1 = _a.sent();
                        console.log(e_1);
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    WebUSBDevice.prototype.getEntropy = function (length) {
        if (length === void 0) { length = 64; }
        return window.crypto.getRandomValues(new Uint8Array(length));
    };
    // This must return a tuple of [returnedBuffer, entireBufferThatWasSent], concatenating if
    // buffers were sent in chunks
    WebUSBDevice.prototype.sendRaw = function (buffer) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                // Temporarily removing queue to debug overflow error potentially caused by concurrent sends
                return [2 /*return*/, this.queue.add(function () { return __awaiter(_this, void 0, void 0, function () {
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, this.write(buffer)];
                                case 1:
                                    _a.sent();
                                    return [2 /*return*/, this.read()];
                            }
                        });
                    }); })];
            });
        });
    };
    WebUSBDevice.prototype.write = function (buff) {
        return __awaiter(this, void 0, void 0, function () {
            var i, segment, padding, fragments, fragmentBuffer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        i = 0;
                        _a.label = 1;
                    case 1:
                        if (!(i < buff.limit)) return [3 /*break*/, 4];
                        segment = buff.toArrayBuffer().slice(i, i + SEGMENT_SIZE);
                        padding = new Array(SEGMENT_SIZE - segment.byteLength + 1).join('\0');
                        fragments = [];
                        fragments.push([63]);
                        fragments.push(segment);
                        fragments.push(padding);
                        fragmentBuffer = bytebuffer_1.default.concat(fragments);
                        return [4 /*yield*/, this.writeChunk(fragmentBuffer)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        i += SEGMENT_SIZE;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    WebUSBDevice.prototype.read = function () {
        return __awaiter(this, void 0, void 0, function () {
            var first, valid, msgLength, buffer, k, offset, next, k;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.readChunk()
                        // Check that buffer starts with: "?##" [ 0x3f, 0x23, 0x23 ]
                        // "?" = USB marker, "##" = KeepKey magic bytes
                        // Message ID is bytes 4-5. Message length starts at byte 6.
                    ];
                    case 1:
                        first = _a.sent();
                        valid = (first.getUint32(0) & 0xffffff00) === 0x3f232300;
                        msgLength = first.getUint32(5);
                        if (!(valid && msgLength >= 0 && msgLength < 131072)) return [3 /*break*/, 5];
                        buffer = new Uint8Array(9 + 2 + msgLength);
                        for (k = 0; k < first.byteLength; k++) {
                            buffer[k] = first.getUint8(k);
                        }
                        offset = first.byteLength;
                        _a.label = 2;
                    case 2:
                        if (!(offset < buffer.length)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.readChunk()
                            // Drop USB "?" packet identifier in the first byte
                        ];
                    case 3:
                        next = _a.sent();
                        // Drop USB "?" packet identifier in the first byte
                        for (k = 1; (k < next.byteLength && offset < buffer.length); k++) {
                            buffer[offset] = next.getUint8(k);
                            offset++;
                        }
                        return [3 /*break*/, 2];
                    case 4: return [2 /*return*/, bytebuffer_1.default.wrap(buffer)];
                    case 5:
                        console.error('Invalid message', { msgLength: msgLength, valid: valid, first: first });
                        return [2 /*return*/, new bytebuffer_1.default(0)];
                }
            });
        });
    };
    WebUSBDevice.prototype.writeChunk = function (buffer) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usbDevice.transferOut(1, buffer.toArrayBuffer())];
            });
        });
    };
    WebUSBDevice.prototype.readChunk = function () {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usbDevice.transferIn(1, SEGMENT_SIZE + 1)];
                    case 1:
                        result = _a.sent();
                        if (!(result.status === 'stall')) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.usbDevice.clearHalt('out', 1)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/, Promise.resolve(result.data)];
                }
            });
        });
    };
    return WebUSBDevice;
}(device_1.default));
exports.default = WebUSBDevice;
//# sourceMappingURL=webUSBDevice.js.map