"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImagePuller = void 0;
const child_process = __importStar(require("child_process"));
class ImagePuller {
    connection;
    context;
    useProgressTracker = false;
    _containerEngine;
    _containerImage;
    _pullPolicy;
    _pullArguments;
    constructor(connection, context, containerEngine, containerImage, pullPolicy, pullArguments) {
        this.connection = connection;
        this.context = context;
        this._containerEngine = containerEngine;
        this._containerImage = containerImage;
        this._pullPolicy = pullPolicy;
        this._pullArguments = pullArguments;
        this.useProgressTracker =
            !!context.clientCapabilities.window?.workDoneProgress;
    }
    async setupImage() {
        let setupComplete = false;
        const imageTag = this._containerImage.split(":", 2)[1] || "latest";
        const imagePresent = this.checkForImage();
        const pullRequired = this.determinePull(imagePresent, imageTag);
        let progressTracker;
        if (this.useProgressTracker) {
            progressTracker = await this.connection.window.createWorkDoneProgress();
        }
        if (pullRequired) {
            this.connection.console.log(`Pulling image '${this._containerImage}' with pull-policy '${this._pullPolicy}' and image-tag '${imageTag}'`);
            try {
                let pullCommand;
                if (this._pullArguments && this._pullArguments !== "") {
                    pullCommand = `${this._containerEngine} pull ${this._containerImage} ${this._pullArguments}`;
                }
                else {
                    pullCommand = `${this._containerEngine} pull ${this._containerImage}`;
                }
                this.connection.console.log(`Running pull command: '${pullCommand}'`);
                if (progressTracker) {
                    progressTracker.begin("execution-environment", undefined, "Pulling Ansible execution environment image...");
                }
                child_process.execSync(pullCommand, {
                    encoding: "utf-8",
                });
                this.connection.console.info(`Container image '${this._containerImage}' pull successful`);
                setupComplete = true;
            }
            catch (error) {
                let errorMsg = `Failed to pull container image ${this._containerEngine} with error '${error}'`;
                errorMsg +=
                    "Check the execution environment image name, connectivity to and permissions for the registry, and try again";
                this.connection.console.error(errorMsg);
                setupComplete = false;
            }
        }
        else {
            setupComplete = true;
        }
        if (progressTracker) {
            progressTracker.done();
        }
        return setupComplete;
    }
    determinePull(imagePresent, imageTag) {
        let pull;
        if (this._pullPolicy === "missing" && !imagePresent) {
            pull = true;
        }
        else if (this._pullPolicy === "always") {
            pull = true;
        }
        else if (this._pullPolicy === "tag" && imageTag === "latest") {
            pull = true;
        }
        else if (this._pullPolicy === "tag" && !imagePresent) {
            pull = true;
        }
        else {
            pull = false;
        }
        return pull;
    }
    checkForImage() {
        try {
            const command = `${this._containerEngine} image inspect ${this._containerImage}`;
            this.connection.console.log(`check for container image with command: '${command}'`);
            child_process.execSync(command, {
                encoding: "utf-8",
            });
            return true;
        }
        catch (error) {
            this.connection.console.log(`'${this._containerImage}' image inspection failed, image assumed to be corrupted or missing`);
            return false;
        }
    }
}
exports.ImagePuller = ImagePuller;
