"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VirtualBoxService = void 0;
const path = require("path");
const os_1 = require("os");
const _ = require("lodash");
const decorators_1 = require("../../../decorators");
const helpers_1 = require("../../../helpers");
const yok_1 = require("../../../yok");
class VirtualBoxService {
    constructor($childProcess, $fs, $hostInfo, $logger) {
        this.$childProcess = $childProcess;
        this.$fs = $fs;
        this.$hostInfo = $hostInfo;
        this.$logger = $logger;
    }
    listVms() {
        return __awaiter(this, void 0, void 0, function* () {
            let result = null;
            let vms = [];
            const vBoxManagePath = yield this.getvBoxManagePath();
            if (vBoxManagePath) {
                result = yield this.$childProcess.trySpawnFromCloseEvent(vBoxManagePath, [
                    "list",
                    "vms",
                ]);
                if (result && result.stdout) {
                    vms = result.stdout
                        .split(os_1.EOL)
                        .filter((row) => !!row)
                        .map((row) => {
                        const [rawName, rawId] = row.split('" ');
                        const id = rawId.substr(1, rawId.length - 2);
                        const name = rawName.substr(1, rawName.length - 1);
                        return { id, name };
                    });
                }
            }
            return { vms, error: result && result.stderr };
        });
    }
    enumerateGuestProperties(id) {
        return __awaiter(this, void 0, void 0, function* () {
            let result = null;
            const vBoxManagePath = yield this.getvBoxManagePath();
            if (vBoxManagePath) {
                result = yield this.$childProcess.trySpawnFromCloseEvent(vBoxManagePath, [
                    "guestproperty",
                    "enumerate",
                    id,
                ]);
            }
            return {
                properties: result && result.stdout,
                error: result && result.stderr,
            };
        });
    }
    getvBoxManageSearchPaths() {
        return __awaiter(this, void 0, void 0, function* () {
            const searchPaths = {
                darwin: ["/usr/local/bin"],
                linux: ["/opt", "/opt/local", "/usr", "/usr/local", "~"],
                win32: [
                    `${process.env["PROGRAMFILES"]}\\Oracle\\VirtualBox`,
                    `${process.env["PROGRAMFILES(X86)"]}\\Oracle\\VirtualBox`,
                ],
            };
            if (this.$hostInfo.isWindows) {
                let searchPath = null;
                try {
                    const result = yield (0, helpers_1.getWinRegPropertyValue)("\\Software\\Oracle\\VirtualBox", "InstallDir");
                    searchPath = result && result.value ? result.value : null;
                }
                catch (err) {
                    this.$logger.trace(`Error while trying to get InstallDir property for \\Software\\Oracle\\VirtualBox. More info: ${err}.`);
                }
                if (searchPath && !_.includes(searchPaths["win32"], searchPath)) {
                    searchPaths["win32"].unshift(searchPath);
                }
            }
            return searchPaths;
        });
    }
    get vBoxManageExecutableNames() {
        return {
            darwin: "VBoxManage",
            linux: "VBoxManage",
            win32: "VBoxManage.exe",
        };
    }
    getvBoxManagePath() {
        return __awaiter(this, void 0, void 0, function* () {
            const searchPaths = (yield this.getvBoxManageSearchPaths())[process.platform];
            const result = searchPaths
                .map((searchPath) => path.join(searchPath, this.vBoxManageExecutableNames[process.platform]))
                .find((searchPath) => this.$fs.exists(searchPath));
            return result;
        });
    }
}
__decorate([
    (0, decorators_1.cache)()
], VirtualBoxService.prototype, "getvBoxManagePath", null);
exports.VirtualBoxService = VirtualBoxService;
yok_1.injector.register("virtualBoxService", VirtualBoxService);
