import subprocess
import time

from .utils import decode_text, isMac, isWindows


def drawToolsInformation(layout):
    if hasToktxInstalled() == False:
        row = layout.row()
        msg = "toktx is not installed or supported. Please install toktx >= 4.3 for optimization"
        row.label(text=msg, icon="ERROR")
        op = row.operator("wm.url_open", text="", icon="URL")
        op.url = "https://docs.needle.tools/getting-started"
        download_url = None
        if isWindows():
            download_url = "https://fwd.needle.tools/needle-engine/toktx/win"
        elif isMac():
            download_url = "https://fwd.needle.tools/needle-engine/toktx/osx-silicon"
        if download_url:
            row2 = layout.row()
            row2.operator("wm.url_open", text="Download Toktx Installer for optimization", icon="URL").url = download_url

        

_lastToktxCheckTime = 0
_toktxVersion = None
_toktxVersionSupported = False

def hasToktxInstalled():
    global _lastToktxCheckTime
    global _toktxVersion
    global _toktxVersionSupported
    now = time.time()
    delay = _toktxVersion is None and 5 or 20
    if now - _lastToktxCheckTime < delay:
        return _toktxVersion is not None and _toktxVersionSupported
    
    _lastToktxCheckTime = now

    toktxCommand = "toktx -v"
    result = subprocess.run(toktxCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    _toktxVersion = decode_text(result.stderr)
    if _toktxVersion is not None:
        _toktxVersion = _toktxVersion.strip()
    _toktxVersionSupported = False
    if result.returncode == 0:
        if _toktxVersion.startswith("toktx v"):
            _toktxVersion = _toktxVersion[7:].strip()
        # is 4.3 or newer
        _toktxVersionSupported = _toktxVersion >= "4.3"
        return _toktxVersionSupported
    _toktxVersion = None
    return False