/* --------------------------------------------------------------------------------------------
* Copyright (c) Remy Suen. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.DockerRegistryClient = void 0;
var https = require("https");
/**
 * The DockerRegistryClient provides a way to communicate with the
 * official Docker registry hosted on Docker Hub.
 */
var DockerRegistryClient = /** @class */ (function () {
    function DockerRegistryClient(logger) {
        this.logger = logger;
    }
    /**
     * Gets the list of tags of the specified image from the Docker registry on Docker Hub.
     *
     * @param image the name of the interested image
     * @param prefix an optional prefix for filtering the list of tags
     * @return a promise that resolves to the specified image's list
     *         of tags, may be empty
     */
    DockerRegistryClient.prototype.getTags = function (image, prefix) {
        var _this = this;
        if (image.indexOf('/') === -1) {
            image = "library/" + image;
        }
        return this.requestToken(image).then(function (data) {
            if (data === null) {
                return [];
            }
            return _this.listTags(data.token, image).then(function (data) {
                if (!prefix) {
                    return data.tags;
                }
                var tags = [];
                for (var _i = 0, _a = data.tags; _i < _a.length; _i++) {
                    var tag = _a[_i];
                    if (tag.indexOf(prefix) === 0) {
                        tags.push(tag);
                    }
                }
                return tags;
            });
        });
    };
    /**
     * Requests for an authentication token from the Docker registry
     * for accessing the given image.
     *
     * @param image the name of the interested image
     * @return a promise that resolves to the authentication token if
     *         successful, or null if an error has occurred
     */
    DockerRegistryClient.prototype.requestToken = function (image) {
        var _this = this;
        return this.performHttpsGet({
            hostname: "auth.docker.io",
            port: 443,
            path: "/token?service=registry.docker.io&scope=repository:" + image + ":pull",
            headers: {
                Accept: "application/json"
            }
        }).catch(function (error) {
            _this.log(error);
            return null;
        });
    };
    /**
     * Queries the registry for the given image's list of tags.
     *
     * @param authToken the authentication token to use for the GET
     * @param image the name of the interested image
     * @return a promise that will resolve to the image's list of
     *         tags, an empty array will be returned if an error
     *         occurs during the GET request
     */
    DockerRegistryClient.prototype.listTags = function (authToken, image) {
        var _this = this;
        return this.performHttpsGet({
            hostname: "registry-1.docker.io",
            port: 443,
            path: "/v2/" + image + "/tags/list",
            headers: {
                Accept: "application/json",
                Authorization: "Bearer " + authToken
            }
        }).catch(function (error) {
            _this.log(error);
            return { tags: [] };
        });
    };
    DockerRegistryClient.prototype.performHttpsGet = function (opts) {
        return new Promise(function (resolve, reject) {
            var request = https.get(opts, function (response) {
                if (response.statusCode !== 200) {
                    // not a 200 OK, reject the promise with the error
                    var error = new Error(response.statusMessage);
                    error.statusCode = response.statusCode;
                    response.resume();
                    reject(error);
                }
                else {
                    var buffer_1 = '';
                    response.on('data', function (data) {
                        buffer_1 += data;
                    });
                    response.on('end', function () {
                        resolve(JSON.parse(buffer_1));
                    });
                }
            });
            request.end();
            request.on('error', function (error) {
                reject(error);
            });
        });
    };
    DockerRegistryClient.prototype.log = function (error) {
        if (this.logger) {
            this.logger.log(error.toString());
        }
    };
    return DockerRegistryClient;
}());
exports.DockerRegistryClient = DockerRegistryClient;
