"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const HttpClient_1 = require("typed-rest-client/HttpClient");
const GalleryInterfaces_1 = require("azure-devops-node-api/interfaces/GalleryInterfaces");
const Serialization_1 = require("azure-devops-node-api/Serialization");
class PublicGalleryAPI {
    constructor(baseUrl, apiVersion = '3.0-preview.1') {
        this.baseUrl = baseUrl;
        this.apiVersion = apiVersion;
        this.client = new HttpClient_1.HttpClient('vsce');
    }
    post(url, data, additionalHeaders) {
        return this.client.post(`${this.baseUrl}/_apis/public${url}`, data, additionalHeaders);
    }
    extensionQuery({ pageNumber = 1, pageSize = 1, sortBy = GalleryInterfaces_1.SortByType.Relevance, sortOrder = GalleryInterfaces_1.SortOrderType.Default, flags = [], criteria = [], assetTypes = [], }) {
        return __awaiter(this, void 0, void 0, function* () {
            const data = JSON.stringify({
                filters: [{ pageNumber, pageSize, criteria }],
                assetTypes,
                flags: flags.reduce((memo, flag) => memo | flag, 0)
            });
            const res = yield this.post('/gallery/extensionquery', data, { Accept: `application/json;api-version=${this.apiVersion}`, 'Content-Type': 'application/json', });
            const raw = JSON.parse(yield res.readBody());
            return Serialization_1.ContractSerializer.deserialize(raw.results[0].extensions, GalleryInterfaces_1.TypeInfo.PublishedExtension, false, false);
        });
    }
    getExtension(extensionId, flags = []) {
        return __awaiter(this, void 0, void 0, function* () {
            const query = { criteria: [{ filterType: GalleryInterfaces_1.ExtensionQueryFilterType.Name, value: extensionId }], flags, };
            const extensions = yield this.extensionQuery(query);
            return extensions.filter(({ publisher: { publisherName: publisher }, extensionName: name }) => extensionId.toLowerCase() === `${publisher}.${name}`.toLowerCase())[0];
        });
    }
}
exports.PublicGalleryAPI = PublicGalleryAPI;
