// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
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());
    });
};
import bent from "bent";
import { ArgumentNullError, Deferred } from "../common/Exports";
export var RestRequestType;
(function (RestRequestType) {
    RestRequestType["Get"] = "GET";
    RestRequestType["Post"] = "POST";
    RestRequestType["Delete"] = "DELETE";
    RestRequestType["File"] = "file";
})(RestRequestType || (RestRequestType = {}));
// accept rest operations via request method and return abstracted objects from server response
export class RestMessageAdapter {
    constructor(configParams) {
        if (!configParams) {
            throw new ArgumentNullError("configParams");
        }
        this.privHeaders = configParams.headers;
        this.privIgnoreCache = configParams.ignoreCache;
    }
    static extractHeaderValue(headerKey, headers) {
        let headerValue = "";
        try {
            const arr = headers.trim().split(/[\r\n]+/);
            const headerMap = {};
            arr.forEach((line) => {
                const parts = line.split(": ");
                const header = parts.shift().toLowerCase();
                const value = parts.join(": ");
                headerMap[header] = value;
            });
            headerValue = headerMap[headerKey.toLowerCase()];
        }
        catch (e) {
            // ignore the error
        }
        return headerValue;
    }
    set options(configParams) {
        this.privHeaders = configParams.headers;
        this.privIgnoreCache = configParams.ignoreCache;
    }
    setHeaders(key, value) {
        this.privHeaders[key] = value;
    }
    request(method, uri, queryParams = {}, body = null) {
        const responseReceivedDeferral = new Deferred();
        const requestCommand = method === RestRequestType.File ? "POST" : method;
        const handleRestResponse = (data, j = {}) => {
            const d = data;
            return {
                data: JSON.stringify(j),
                headers: JSON.stringify(data.headers),
                json: j,
                ok: data.statusCode >= 200 && data.statusCode < 300,
                status: data.statusCode,
                statusText: j.error ? j.error.message : d.statusText ? d.statusText : d.statusMessage
            };
        };
        const send = (postData) => {
            const sendRequest = bent(uri, requestCommand, this.privHeaders, 200, 201, 202, 204, 400, 401, 402, 403, 404);
            const params = this.queryParams(queryParams) === "" ? "" : `?${this.queryParams(queryParams)}`;
            sendRequest(params, postData).then((data) => __awaiter(this, void 0, void 0, function* () {
                if (method === RestRequestType.Delete || data.statusCode === 204) {
                    // No JSON from Delete and reset (204) operations
                    responseReceivedDeferral.resolve(handleRestResponse(data));
                }
                else {
                    try {
                        const j = yield data.json();
                        responseReceivedDeferral.resolve(handleRestResponse(data, j));
                    }
                    catch (_a) {
                        responseReceivedDeferral.resolve(handleRestResponse(data));
                    }
                }
            })).catch((error) => {
                responseReceivedDeferral.reject(error);
            });
        };
        if (this.privIgnoreCache) {
            this.privHeaders["Cache-Control"] = "no-cache";
        }
        if (method === RestRequestType.Post && body) {
            this.privHeaders["content-type"] = "application/json";
            this.privHeaders["Content-Type"] = "application/json";
        }
        send(body);
        return responseReceivedDeferral.promise;
    }
    queryParams(params = {}) {
        return Object.keys(params)
            .map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(params[k]))
            .join("&");
    }
}

//# sourceMappingURL=RestMessageAdapter.js.map
