"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 logger_1 = require("../../logger");
const url_1 = require("../url");
const _1 = require(".");
const MAX_PAGES = 100;
const MAX_PAGELEN = 100;
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 resolvedURL = (0, url_1.parseUrl)((0, url_1.resolveBaseUrl)(baseUrl, path));
        // istanbul ignore if: this should never happen
        if (is_1.default.nullOrUndefined(resolvedURL)) {
            logger_1.logger.error(`Bitbucket: cannot parse path ${path}`);
            throw new Error(`Bitbucket: cannot parse path ${path}`);
        }
        if (opts.paginate && !hasPagelen(resolvedURL)) {
            const pagelen = opts.pagelen ?? MAX_PAGELEN;
            resolvedURL.searchParams.set('pagelen', pagelen.toString());
        }
        const result = await super.request(resolvedURL.toString(), opts);
        if (opts.paginate && isPagedResult(result.body)) {
            const resultBody = result.body;
            let page = 1;
            let nextURL = resultBody.next;
            while (is_1.default.nonEmptyString(nextURL) && page <= MAX_PAGES) {
                const nextResult = await super.request(nextURL, options);
                resultBody.values.push(...nextResult.body.values);
                nextURL = nextResult.body?.next;
                page += 1;
            }
            // Override other page-related attributes
            resultBody.pagelen = resultBody.values.length;
            resultBody.size = page > MAX_PAGES ? undefined : resultBody.values.length;
            resultBody.next = page > MAX_PAGES ? undefined : nextURL;
        }
        return result;
    }
}
exports.BitbucketHttp = BitbucketHttp;
function hasPagelen(url) {
    return !is_1.default.nullOrUndefined(url.searchParams.get('pagelen'));
}
function isPagedResult(obj) {
    return is_1.default.nonEmptyObject(obj) && Array.isArray(obj.values);
}
//# sourceMappingURL=bitbucket.js.map