import os
import shutil
import subprocess
import sys
from make.terminal import print_error, print_green, print_yellow

if sys.platform == "win32":
    import winreg

def mikero_windows_registry(path, access=winreg.KEY_READ):
    try:
        return winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Mikero\{}".format(path), access=access)
    except FileNotFoundError:
        try:
            return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\Mikero\{}".format(path), access=access)
        except FileNotFoundError:
            try:
                return winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Wow6432Node\Mikero\{}".format(path), access=access)
            except FileNotFoundError:
                return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\Wow6432Node\Mikero\{}".format(path), access=access)

def find_depbo_tools():
    """Use registry entries to find DePBO-based tools."""
    # try running pboProject once if it's not in registry
    try:
        pboProject = mikero_windows_registry("pboProject")
        print(f"pboProject found normally via registry")
    except:
        print(f"pboProject not in registry")
        pboProject = shutil.which('pboProject')
        if (pboProject is None):
            print("pboProject not in sys path")
        else:
            print(f"pboProject startup")
            ret = subprocess.call([pboProject, "-P"])

    requiredToolPaths = {"pboProject": None, "rapify": None, "MakePbo": None}
    failed = False

    for tool in requiredToolPaths:
        try:
            k = mikero_windows_registry(tool)
            path = winreg.QueryValueEx(k, "exe")[0]
        except FileNotFoundError:
            print_error("Could not find {}".format(tool))
            failed = True
        else:
            #Strip any quotations from the path due to a MikeRo tool bug which leaves a trailing space in some of its registry paths.
            requiredToolPaths[tool] = path.strip('"')
            print_green("Found {}.".format(tool))
        finally:
            winreg.CloseKey(k)

    if failed:
        raise Exception("BadDePBO", "DePBO tools not installed correctly")

    return requiredToolPaths

def pboproject_settings():
    """Use registry entries to configure needed pboproject settings."""
    value_exclude = "thumbs.db,*.txt,*.h,*.dep,*.cpp,*.bak,*.png,*.log,*.pew,source,*.tga"

    try:
        pbok = mikero_windows_registry(r"pboProject")
        try:
            k = winreg.OpenKey(pbok, "Settings", access=winreg.KEY_SET_VALUE)
        except:
            print_yellow("WARNING: creating pboProject/Settings reg manually")
            print_yellow("This should have happened before running make.py")
            k = winreg.CreateKeyEx(pbok, "Settings", access=winreg.KEY_SET_VALUE)
        winreg.SetValueEx(k, "m_exclude", 0, winreg.REG_SZ, value_exclude)
        winreg.SetValueEx(k, "m_exclude2", 0, winreg.REG_SZ, value_exclude)
        winreg.SetValueEx(k, "wildcard_exclude_from_pbo_normal", 0, winreg.REG_SZ, value_exclude)
        winreg.SetValueEx(k, "wildcard_exclude_from_pbo_unbinarised_missions", 0, winreg.REG_SZ, value_exclude)
    except:
        raise Exception("BadDePBO", "pboProject not installed correctly, make sure to run it at least once")
    finally:
        winreg.CloseKey(k)
        winreg.CloseKey(pbok)

