// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import { ClientBinaryOpcode, BinaryOpcode } from '@foxglove/ws-protocol';
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export function makeServiceCallRequest(request) {
    const encoding = textEncoder.encode(request.encoding);
    const payload = new Uint8Array(1 + 4 + 4 + 4 + encoding.length + request.data.byteLength);
    const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
    let offset = 0;
    view.setUint8(offset, ClientBinaryOpcode.SERVICE_CALL_REQUEST);
    offset += 1;
    view.setUint32(offset, request.serviceId, true);
    offset += 4;
    view.setUint32(offset, request.callId, true);
    offset += 4;
    view.setUint32(offset, request.encoding.length, true);
    offset += 4;
    payload.set(encoding, offset);
    offset += encoding.length;
    const data = new Uint8Array(request.data.buffer, request.data.byteOffset, request.data.byteLength);
    payload.set(data, offset);
    return new DataView(payload.buffer);
}
export function parseMessage(view) {
    let offset = 0;
    const op = view.getUint8(offset);
    offset += 1;
    const subscriptionId = view.getUint32(offset, true);
    offset += 4;
    const timestamp = view.getBigUint64(offset, true);
    offset += 8;
    const data = new DataView(view.buffer, offset);
    return { op, subscriptionId, timestamp, data };
}
export function parseServiceCallResponse(view) {
    let offset = 0;
    const op = view.getUint8(offset);
    offset += 1;
    const serviceId = view.getUint32(offset, true);
    offset += 4;
    const callId = view.getUint32(offset, true);
    offset += 4;
    const encodingLength = view.getUint32(offset, true);
    offset += 4;
    const encodingBytes = new DataView(view.buffer, offset, encodingLength);
    const encoding = textDecoder.decode(encodingBytes);
    offset += encodingLength;
    const data = new DataView(view.buffer, offset, view.buffer.byteLength - offset);
    return { op, serviceId, callId, encoding, data };
}
export function parseFoxgloveMessage(view) {
    const op = view.getUint8(0);
    if (op === BinaryOpcode.MESSAGE_DATA) {
        return parseMessage(view);
    }
    else if (op === BinaryOpcode.SERVICE_CALL_RESPONSE) {
        return parseServiceCallResponse(view);
    }
    return null;
}
//# sourceMappingURL=foxglove-protocol.js.map