/*
 * Copyright (c) 2019 NumberFour AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   NumberFour AG - Initial API and implementation
 */


import * as fs from "fs";
import * as path from "path";
import * as childProcess from "child_process";
import {RESOURCES_DIR} from 'Globals';

const JAVA_SOURCE_CLASSNAME = "PrintJavaVersion";
const JAVA_SOURCE_FILE = path.resolve(RESOURCES_DIR, JAVA_SOURCE_CLASSNAME + ".java");
const JAVA_CLASS_FILE = path.resolve(RESOURCES_DIR, JAVA_SOURCE_CLASSNAME + ".class");


/**
 * Returns the feature segment of the installed JRE version or null otherwise.
 */
export public function detectJavaVersion() : int {
    if (!fs.existsSync(JAVA_CLASS_FILE)) {
        const procCompile = childProcess.spawnSync('javac', [JAVA_SOURCE_FILE]);
        if (procCompile.error) {
            throw procCompile.error;
        }
    }

    // Compiling was successful
    const procRun = childProcess.spawnSync('java', [JAVA_SOURCE_FILE]);
    if (procRun.error) {
        throw procRun.error;
    }
    if (procRun.stderr && procRun.stderr.toString()) {
        throw procRun.stderr;
    }

    // Executing PrintJavaVersion was successful
    const versionFeature = procRun.stdout.toString().trim();
    if (!versionFeature) {
        throw "Missing return value of " + JAVA_SOURCE_FILE;
    }

    const version = parseInt(versionFeature);
    if (!version) {
        throw "Invalid Java version " + version;
    }

    return version;
}
