"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRequestHeadersFromMessage = getRequestHeadersFromMessage;
const UTF_16_js_1 = require("../../utils/UTF_16.js");
const arrayBufferToString_js_1 = require("../../utils/arrayBufferToString.js");
const getElementsByName_js_1 = require("../../xml/getElementsByName.js");
const parseXml_js_1 = require("../../xml/parseXml.js");
const CONTENT_TYPE_js_1 = require("../common/CONTENT_TYPE.js");
const HTTP_HEADERS_js_1 = require("../common/HTTP_HEADERS.js");
const TEXT_XML_UTF8_js_1 = require("../common/TEXT_XML_UTF8.js");
/**
 * Gets the PlayReady license request headers from the MediaKeyMessageEvent.
 *
 * @param message - An ArrayBuffer from the content decryption module.
 * @param encoding - The message encoding type. Default is UTF-16.
 * @returns Request headers.
 *
 * @group DRM
 * @beta
 *
 * @example
 * {@includeCode ../../../test/drm/playready/getRequestHeadersFromMessage.test.ts#example}
 */
function getRequestHeadersFromMessage(message, encoding = UTF_16_js_1.UTF_16) {
    var _a, _b, _c, _d;
    const headers = {};
    // If message format configured/defaulted to utf-16 AND number of bytes is odd,
    // assume 'unwrapped' raw CDM message.
    if (encoding === UTF_16_js_1.UTF_16 && message && message.byteLength % 2 === 1) {
        headers[CONTENT_TYPE_js_1.CONTENT_TYPE] = TEXT_XML_UTF8_js_1.TEXT_XML_UTF8;
        return headers;
    }
    const msg = (0, arrayBufferToString_js_1.arrayBufferToString)(message, encoding);
    const xml = (0, parseXml_js_1.parseXml)(msg);
    const httpHeaders = (0, getElementsByName_js_1.getElementsByName)(xml, HTTP_HEADERS_js_1.HTTP_HEADERS)[0].childNodes;
    for (const header of httpHeaders) {
        const name = (_b = (_a = (0, getElementsByName_js_1.getElementsByName)(header, 'name')[0]) === null || _a === void 0 ? void 0 : _a.childNodes[0]) === null || _b === void 0 ? void 0 : _b.nodeValue;
        const value = (_d = (_c = (0, getElementsByName_js_1.getElementsByName)(header, 'value')[0]) === null || _c === void 0 ? void 0 : _c.childNodes[0]) === null || _d === void 0 ? void 0 : _d.nodeValue;
        if (name && value) {
            headers[name] = value;
        }
    }
    // Some versions of the PlayReady CDM return 'Content' instead of 'Content-Type'.
    // This does not adhere to the W3C spec and license servers may reject the request.
    if (headers.hasOwnProperty('Content')) {
        headers[CONTENT_TYPE_js_1.CONTENT_TYPE] = headers['Content'];
        delete headers['Content'];
    }
    // Set 'Content-Type' header by default if not provided in the the CDM message
    // or if the message is unwrapped.
    if (!headers.hasOwnProperty(CONTENT_TYPE_js_1.CONTENT_TYPE)) {
        headers[CONTENT_TYPE_js_1.CONTENT_TYPE] = TEXT_XML_UTF8_js_1.TEXT_XML_UTF8;
    }
    return headers;
}
//# sourceMappingURL=getRequestHeadersFromMessage.js.map