"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponseStore = void 0;
const tslib_1 = require("tslib");
const json_1 = require("@stoplight/json");
const axios_1 = tslib_1.__importDefault(require("axios"));
const mobx_1 = require("mobx");
const constants_1 = require("../../constants");
const arrayBuffer_1 = require("../../utils/arrayBuffer");
const getResponseType_1 = require("../../utils/getResponseType");
let ResponseStore = (() => {
    class ResponseStore {
        constructor(status, statusCode, headers, rawbody, isMockedResponse, violations, error) {
            this.responseTime = 0;
            this.status = status;
            this.statusCode = statusCode;
            this.headers = headers;
            this.raw = rawbody;
            this.isMockedResponse = isMockedResponse;
            this.error = error;
            this.violations = violations;
        }
        static createEmpty() {
            return new ResponseStore('', 0, {}, new ArrayBuffer(0), false, []);
        }
        static fromNetworkResponse(response) {
            let violations = [];
            const violationsHeader = response.headers['sl-violations'];
            if (violationsHeader) {
                violations = json_1.safeParse(response.headers['sl-violations']) || [];
            }
            return new ResponseStore('Completed', response.status, response.headers, response.data || new ArrayBuffer(0), false, violations);
        }
        static fromAxiosError(err) {
            if (axios_1.default.isCancel(err)) {
                return new ResponseStore('Canceled', 0, {}, new ArrayBuffer(0), false, [], undefined);
            }
            else if (err.response) {
                return this.fromNetworkResponse(err.response);
            }
            else {
                const error = new Error(`${err.message ? `${err.message}\n\n` : ''}The API did not return a response. Is it running and accessible?\n\nIf you are sending this request from a web browser, does the API support CORS?`);
                return new ResponseStore('Error', 0, {}, new ArrayBuffer(0), false, [], error);
            }
        }
        static fromMockObjectResponse(responseObject) {
            const stringData = JSON.stringify(responseObject.data);
            const abData = (stringData && arrayBuffer_1.stringToArrayBuffer(stringData)) || new Uint8Array();
            return new ResponseStore('Completed', responseObject.status, responseObject.headers || {}, abData, true, responseObject.violations);
        }
        static fromError(err) {
            return new ResponseStore('Error', 0, {}, new ArrayBuffer(0), false, [], err);
        }
        get statusText() {
            if (this.status === 'Completed') {
                return `${this.statusCode} ${constants_1.HttpCodeDescriptions[this.statusCode]}`;
            }
            return this.status;
        }
        get responseType() {
            return getResponseType_1.getResponseType(this.contentTypeHeaderValue) || (this.bodyJson !== undefined ? 'json' : '');
        }
        get contentTypeHeaderValue() {
            for (const header in this.headers) {
                if (this.headers[header] && header.toLowerCase() === 'content-type') {
                    return this.headers[header];
                }
            }
            return '';
        }
        get body() {
            const headerResponseType = getResponseType_1.getResponseType(this.contentTypeHeaderValue);
            try {
                if (headerResponseType === 'img') {
                    return `data:${this.contentTypeHeaderValue};base64,${arrayBuffer_1.arrayBufferToBase64String(this.raw)}`;
                }
                else {
                    return arrayBuffer_1.arrayBufferUtf8ToString(this.raw) || '';
                }
            }
            catch (error) {
                console.error('Error parsing response body', error.message);
                return '';
            }
        }
        get bodyJson() {
            return json_1.safeParse(this.body);
        }
    }
    tslib_1.__decorate([
        mobx_1.observable.ref,
        tslib_1.__metadata("design:type", ArrayBuffer)
    ], ResponseStore.prototype, "raw", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", Number)
    ], ResponseStore.prototype, "statusCode", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", String)
    ], ResponseStore.prototype, "status", void 0);
    tslib_1.__decorate([
        mobx_1.observable.ref,
        tslib_1.__metadata("design:type", Object)
    ], ResponseStore.prototype, "headers", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", Error)
    ], ResponseStore.prototype, "error", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", Boolean)
    ], ResponseStore.prototype, "isMockedResponse", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", Array)
    ], ResponseStore.prototype, "violations", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", Number)
    ], ResponseStore.prototype, "responseTime", void 0);
    tslib_1.__decorate([
        mobx_1.observable,
        tslib_1.__metadata("design:type", Object)
    ], ResponseStore.prototype, "originalRequest", void 0);
    tslib_1.__decorate([
        mobx_1.computed,
        tslib_1.__metadata("design:type", Object),
        tslib_1.__metadata("design:paramtypes", [])
    ], ResponseStore.prototype, "statusText", null);
    tslib_1.__decorate([
        mobx_1.computed,
        tslib_1.__metadata("design:type", String),
        tslib_1.__metadata("design:paramtypes", [])
    ], ResponseStore.prototype, "responseType", null);
    tslib_1.__decorate([
        mobx_1.computed,
        tslib_1.__metadata("design:type", Object),
        tslib_1.__metadata("design:paramtypes", [])
    ], ResponseStore.prototype, "contentTypeHeaderValue", null);
    tslib_1.__decorate([
        mobx_1.computed,
        tslib_1.__metadata("design:type", String),
        tslib_1.__metadata("design:paramtypes", [])
    ], ResponseStore.prototype, "body", null);
    tslib_1.__decorate([
        mobx_1.computed,
        tslib_1.__metadata("design:type", Object),
        tslib_1.__metadata("design:paramtypes", [])
    ], ResponseStore.prototype, "bodyJson", null);
    return ResponseStore;
})();
exports.ResponseStore = ResponseStore;
//# sourceMappingURL=response.js.map