import re
import subprocess
import sys
from typing import Optional

from clarabot_nano.utility.subprocess.spawn import platform_fix_spawn_child_kwargs

JAVA_VERSION_RE = re.compile(r'^(?:openjdk|java) version "(\d+)\.(\d+)(?:[_.]\d+)*"')


def get_java_version_output(java_exec_path: str = None) -> str:
    return get_java_command_output("-version", java_exec_path=java_exec_path)


def get_java_command_output(*args: str, java_exec_path: str = None) -> str:
    if not java_exec_path:
        java_exec_path = "java.exe" if sys.platform.startswith("win") else "java"
    return subprocess.check_output(
        [java_exec_path, *args],
        **platform_fix_spawn_child_kwargs(dict(stderr=subprocess.STDOUT, encoding="utf-8", universal_newlines=True))
    )


def parse_java_major_version(version_output: str) -> Optional[int]:
    first_line = version_output.strip().split("\n", maxsplit=1)[0].strip()
    m = JAVA_VERSION_RE.match(first_line)
    if m:
        major = int(m.group(1))
        if major == 1:
            return int(m.group(2))  # old version string "1.8.0" -> Java 8
        return major
