"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.request = exports.requestUrl = void 0;
const http = require("http");
const https = require("https");
const CdmHttpResponse_1 = require("../Utilities/Network/CdmHttpResponse");
function requestUrl(url, method, requestTimeout, content = undefined, headers = undefined) {
    return __awaiter(this, void 0, void 0, function* () {
        const protocolIndex = url.indexOf('://');
        if (protocolIndex === -1) {
            return Promise.reject('Protocol not present in the URL');
        }
        const pathIndex = url.indexOf('/', protocolIndex + 3);
        const hostIndex = pathIndex !== -1 ? pathIndex : url.length;
        const protocol = url.slice(0, protocolIndex);
        const host = url.slice(protocolIndex + 3, hostIndex);
        const path = pathIndex !== -1 ? url.slice(pathIndex) : '';
        return request(protocol, host, path, method, requestTimeout, content, headers);
    });
}
exports.requestUrl = requestUrl;
function request(protocol, host, path, method, requestTimeout, content = undefined, headers = undefined) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resolve, reject) => {
            let lib;
            switch (protocol) {
                case 'https':
                    lib = https;
                    break;
                case 'http':
                    lib = http;
                    break;
                default:
                    reject(new Error('Protocol does not exist.'));
                    return;
            }
            const options = {
                hostname: host,
                path: path,
                port: undefined,
                method: method,
                headers: headers,
            };
            // If the host has a port on it, break it down. E.g.: 'localhost:8000'
            const portIndex = host.indexOf(':');
            if (portIndex !== -1) {
                options.hostname = host.slice(0, portIndex);
                options.port = host.slice(portIndex + 1);
            }
            const req = lib.request(options, (res) => {
                const arr = [];
                res.on('data', (chunk) => {
                    arr.push(chunk);
                });
                res.on('end', () => {
                    const cdmHttpResponse = new CdmHttpResponse_1.CdmHttpResponse();
                    const buf = Buffer.concat(arr);
                    // Process results from incoming message directly here and save the results to the newly created CDM Http response object.
                    cdmHttpResponse.content = buf.toString('utf-8');
                    cdmHttpResponse.statusCode = res.statusCode;
                    // Successful responses are in the 2xx format.
                    cdmHttpResponse.isSuccessful = Math.floor(cdmHttpResponse.statusCode / 100) === 2;
                    cdmHttpResponse.reason = res.statusMessage;
                    if (res.headers !== undefined) {
                        const headers = Object.entries(res.headers);
                        // Covert the incoming headers back to the CDM Http headers format.
                        headers.forEach((header) => {
                            let headerValue = undefined;
                            if (header[1] instanceof Array) {
                                headerValue = header[1].join(',');
                            }
                            else {
                                headerValue = header[1];
                            }
                            cdmHttpResponse.responseHeaders.set(header[0], headerValue);
                        });
                    }
                    resolve(cdmHttpResponse);
                });
                res.on('error', (err) => {
                    reject(err);
                });
            });
            req.on('socket', (socket) => {
                // Set the timeout on the socket.
                socket.setTimeout(requestTimeout);
                socket.on('timeout', () => req.abort());
            });
            req.on('error', (err) => {
                reject(err);
            });
            if (content !== undefined) {
                // Be sure to set the content in the case of a POST or PUT HTTP request.
                req.write(content, 'utf-8');
            }
            req.end();
        });
    });
}
exports.request = request;
;
//# sourceMappingURL=request.js.map