"use strict";
var __extends = (this && this.__extends) || (function () {
    var 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 function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var getTwirpError = function (err) {
    var resp = err.response;
    var twirpError = {
        code: 'unknown',
        msg: 'unknown error'
    };
    if (resp) {
        var headers = resp.headers;
        var data = resp.data;
        if (headers['content-type'] === 'application/json') {
            var s = data.toString();
            if (s === "[object ArrayBuffer]") {
                s = String.fromCharCode.apply(null, new Uint8Array(data));
            }
            try {
                twirpError = JSON.parse(s);
            }
            catch (e) {
                twirpError.msg = "JSON.parse() error: " + e.toString();
            }
        }
    }
    return twirpError;
};
exports.createTwirpAdapter = function (axios, methodLookup) {
    return function (method, requestData, callback) {
        axios({
            method: 'POST',
            url: methodLookup(method),
            headers: {
                'Content-Type': 'application/protobuf'
            },
            // required to get an arraybuffer of the actual size, not the 8192 buffer pool that protobuf.js uses
            // see: https://github.com/dcodeIO/protobuf.js/issues/852
            data: requestData.slice(),
            responseType: 'arraybuffer'
        })
            .then(function (resp) {
            callback(null, new Uint8Array(resp.data));
        })
            .catch(function (err) {
            var twirpErr = getTwirpError(err);
            var status = err.response ? err.response.status : 500;
            callback(new TwirpHTTPError(twirpErr.code, twirpErr.msg, status), null);
        });
    };
};
var TwirpHTTPError = /** @class */ (function (_super) {
    __extends(TwirpHTTPError, _super);
    function TwirpHTTPError(code, msg, status) {
        var _newTarget = this.constructor;
        var _this = 
        // 'Error' breaks prototype chain here
        _super.call(this, code + "(" + status + "): " + msg) || this;
        _this.code = code;
        _this.msg = msg;
        _this.status = status;
        // restore prototype chain
        var actualProto = _newTarget.prototype;
        Object.setPrototypeOf(_this, actualProto);
        return _this;
    }
    return TwirpHTTPError;
}(Error));
exports.TwirpHTTPError = TwirpHTTPError;
