"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnonymousServiceRequest = exports.AuthorizedServiceRequest = exports.ResponseHandler = exports.RequestOptions = exports.logErrorResponse = void 0;
var axios_1 = __importDefault(require("axios"));
var lodash_1 = require("lodash");
var BringgException_1 = require("../Core/BringgException");
var Logger_1 = __importDefault(require("../Core/Logger"));
var abort_1 = require("../utils/abort");
var version = '_SDK_VERSION_';
function logErrorResponse(response) {
    var data = response.data, status = response.status;
    try {
        Logger_1.default.error(response.config.method.toUpperCase(), response.config.url, status);
    }
    catch (e) {
        //
    }
    try {
        Logger_1.default.info(response.config.method.toUpperCase(), response.config.url, status, data);
    }
    catch (e) {
        //
    }
    try {
        Logger_1.default.debug(response);
    }
    catch (e) {
        //
    }
}
exports.logErrorResponse = logErrorResponse;
var DEFAULT_TIMEOUT = 120000;
var RequestOptions = /** @class */ (function () {
    function RequestOptions(clientId, timeout, queryString, authenticationToken, headers, responseType, signal) {
        // NiceToHave: move headers to HttpHeaders class
        this.headers = __assign(__assign({ 'Content-Type': 'application/json' }, headers), { 'sdk-version': version, Client: clientId });
        this.timeout = timeout;
        this.validateStatus = lodash_1.stubTrue;
        if (queryString) {
            this.params = queryString;
        }
        if (authenticationToken) {
            this.headers['Authorization'] = "Token token=".concat(authenticationToken);
        }
        if (responseType) {
            this.responseType = responseType;
        }
        if (signal) {
            this.signal = signal;
        }
    }
    RequestOptions.new = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.clientId, clientId = _c === void 0 ? 'Bringg Dashboard' : _c, _d = _b.timeout, timeout = _d === void 0 ? DEFAULT_TIMEOUT : _d, queryString = _b.queryString, authenticationToken = _b.authenticationToken, headers = _b.headers, responseType = _b.responseType, signal = _b.signal;
        return new RequestOptions(clientId, timeout || DEFAULT_TIMEOUT, queryString, authenticationToken, headers, responseType, signal);
    };
    return RequestOptions;
}());
exports.RequestOptions = RequestOptions;
var ResponseHandler = /** @class */ (function () {
    function ResponseHandler(response, signal) {
        this.axiosPromise = response;
        this.signal = signal;
    }
    ResponseHandler.prototype.handle = function (consumer) {
        return __awaiter(this, void 0, void 0, function () {
            var axiosResponse, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if ((0, lodash_1.isUndefined)(consumer)) {
                            throw new Error('consumer must be defined');
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.axiosPromise];
                    case 2:
                        axiosResponse = _a.sent();
                        return [2 /*return*/, consumer(axiosResponse)];
                    case 3:
                        e_1 = _a.sent();
                        if (axios_1.default.isCancel(e_1)) {
                            (0, abort_1.throwAbortError)(this.signal, 'Request Aborted');
                        }
                        if (e_1 instanceof BringgException_1.BringgException) {
                            throw e_1;
                        }
                        return [2 /*return*/, consumer(e_1)];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    return ResponseHandler;
}());
exports.ResponseHandler = ResponseHandler;
function get(axiosInstance, host, uri, queryString, signal) {
    return new ResponseHandler(axiosInstance.get("".concat(host).concat(uri), { params: queryString, signal: signal }), signal);
}
function post(axiosInstance, host, uri, queryString, payload, signal) {
    return new ResponseHandler(axiosInstance.post("".concat(host).concat(uri), payload, { params: queryString, signal: signal }), signal);
}
function put(axiosInstance, host, uri, queryString, payload, signal) {
    return new ResponseHandler(axiosInstance.put("".concat(host).concat(uri), payload, { params: queryString, signal: signal }), signal);
}
function patch(axiosInstance, host, uri, queryString, payload, signal) {
    return new ResponseHandler(axiosInstance.patch("".concat(host).concat(uri), payload, { params: queryString, signal: signal }), signal);
}
function remove(axiosInstance, host, uri, queryString, payload, signal) {
    return new ResponseHandler(axiosInstance.delete("".concat(host).concat(uri), { params: queryString, data: payload, signal: signal }), signal);
}
function routify(axiosInstance, endpoint, route, routeParams, queryString, payload, signal) {
    switch (route.httpMethod) {
        case 0 /* HttpMethod.GET */:
            return get(axiosInstance, endpoint.encode(), route.applyParams(routeParams), queryString, signal);
        case 1 /* HttpMethod.POST */:
            return post(axiosInstance, endpoint.encode(), route.applyParams(routeParams), queryString, payload, signal);
        case 2 /* HttpMethod.PUT */:
            return put(axiosInstance, endpoint.encode(), route.applyParams(routeParams), queryString, payload, signal);
        case 3 /* HttpMethod.PATCH */:
            return patch(axiosInstance, endpoint.encode(), route.applyParams(routeParams), queryString, payload, signal);
        case 4 /* HttpMethod.DELETE */:
            return remove(axiosInstance, endpoint.encode(), route.applyParams(routeParams), queryString, payload, signal);
    }
}
function wrapWithInterceptors(axios) {
    axios.interceptors.request.use(function (req) {
        var method = req.method, url = req.url, params = req.params, headers = req.headers, data = req.data;
        try {
            Logger_1.default.debug('REQUEST:', method.toUpperCase(), url);
        }
        catch (e) {
            //
        }
        try {
            Logger_1.default.trace('REQUEST-query-string:', params);
            Logger_1.default.trace('REQUEST-headers:', headers);
            Logger_1.default.trace('REQUEST-data:', data);
        }
        catch (e) {
            //
        }
        return req;
    });
    axios.interceptors.response.use(function (res) {
        var statusText = res.statusText, status = res.status, headers = res.headers, data = res.data;
        try {
            Logger_1.default.debug('RESPONSE:', res.config.url, status, statusText);
        }
        catch (e) {
            //
        }
        try {
            Logger_1.default.trace('RESPONSE-headers:', headers);
            Logger_1.default.trace('RESPONSE-data:', data);
        }
        catch (e) {
            //
        }
        return res;
    });
    return axios;
}
function axiosInstance(clientId, authenticationToken, headers, responseType, timeout, signal) {
    return wrapWithInterceptors(axios_1.default.create(RequestOptions.new({ clientId: clientId, authenticationToken: authenticationToken, headers: headers, responseType: responseType, timeout: timeout, signal: signal })));
}
function anonymousAxiosInstance(clientId, headers, signal) {
    return wrapWithInterceptors(axios_1.default.create(RequestOptions.new({ clientId: clientId, headers: headers, signal: signal })));
}
var AuthorizedServiceRequest = /** @class */ (function () {
    function AuthorizedServiceRequest(clientId, authToken) {
        this.authToken = authToken;
        this.clientId = clientId;
    }
    AuthorizedServiceRequest.prototype.invoke = function (endpoint, route, routeParams, queryString, payload, headers, responseType, timeout, signal) {
        if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
            (0, abort_1.throwAbortError)(signal, 'Request aborted (before even started the request)');
        }
        return routify(axiosInstance(this.clientId, this.authToken, headers, responseType, timeout), endpoint, route, routeParams, queryString, payload, signal);
    };
    return AuthorizedServiceRequest;
}());
exports.AuthorizedServiceRequest = AuthorizedServiceRequest;
var AnonymousServiceRequest = /** @class */ (function () {
    function AnonymousServiceRequest(clientId, headers) {
        this.clientId = clientId;
        this.headers = headers;
    }
    AnonymousServiceRequest.prototype.invoke = function (endpoint, route, routeParams, queryString, payload, signal) {
        if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
            (0, abort_1.throwAbortError)(signal, 'Request aborted (before even started the request)');
        }
        return routify(anonymousAxiosInstance(this.clientId, this.headers, signal), endpoint, route, routeParams, queryString, payload);
    };
    return AnonymousServiceRequest;
}());
exports.AnonymousServiceRequest = AnonymousServiceRequest;
//# sourceMappingURL=ServiceRequest.js.map