"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BitbucketHttp = exports.setBaseUrl = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const url_1 = require("../url");
const _1 = require(".");
let baseUrl = 'https://api.bitbucket.org/';
const setBaseUrl = (url) => {
    baseUrl = url;
};
exports.setBaseUrl = setBaseUrl;
class BitbucketHttp extends _1.Http {
    constructor(type = 'bitbucket', options) {
        super(type, options);
    }
    async request(path, options) {
        const opts = { baseUrl, ...options };
        const result = await super.request(path, opts);
        if (opts.paginate && isPagedResult(result.body)) {
            const resultBody = result.body;
            let nextPage = getPageFromURL(resultBody.next);
            while (is_1.default.nonEmptyString(nextPage)) {
                const nextPath = getNextPagePath(path, nextPage);
                // istanbul ignore if
                if (is_1.default.nullOrUndefined(nextPath)) {
                    break;
                }
                const nextResult = await super.request(nextPath, options);
                resultBody.values.push(...nextResult.body.values);
                nextPage = getPageFromURL(nextResult.body?.next);
            }
            // Override other page-related attributes
            resultBody.pagelen = resultBody.values.length;
            resultBody.size = resultBody.values.length;
            resultBody.next = undefined;
        }
        return result;
    }
}
exports.BitbucketHttp = BitbucketHttp;
function getPageFromURL(url) {
    const resolvedURL = (0, url_1.parseUrl)(url);
    if (is_1.default.nullOrUndefined(resolvedURL)) {
        return null;
    }
    return resolvedURL.searchParams.get('page');
}
function getNextPagePath(path, nextPage) {
    const resolvedURL = (0, url_1.parseUrl)((0, url_1.resolveBaseUrl)(baseUrl, path));
    // istanbul ignore if
    if (is_1.default.nullOrUndefined(resolvedURL)) {
        return null;
    }
    resolvedURL.searchParams.set('page', nextPage);
    return resolvedURL.toString();
}
function isPagedResult(obj) {
    return is_1.default.nonEmptyObject(obj) && Array.isArray(obj.values);
}
//# sourceMappingURL=bitbucket.js.map