import winreg
import os

fileContent = "v10mwY8DF9HVEYwDTti3zQU9dk9YD8JSR3M"

def WriteErrorMessage(text: str):
    errorPrepend = "[37m[41m"    # Makes Text Red
    formatterAppend = "[0m"        # Returns text to normal
    print(errorPrepend + text + formatterAppend)

def GetAppDataPath() -> str:
    appdata_path = os.getenv('APPDATA')
    folder = os.path.join(appdata_path, 'ModuleWorks')
    if(not os.path.exists(folder)):
        os.makedirs(folder)
    return os.path.join(folder, 'plugins.lic')

def GetInstallerPath() -> str:
    # Connect to the registry
    aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

    # Specify the registry key path
    key_path = r'Software\ModuleWorks'

    try:
        # Open the key
        key = winreg.OpenKey(aReg, key_path)

        result, _ = winreg.QueryValueEx(key, "PluginInstallerPath")
        print('Installer found: ' + result)
        return result
    except:
        WriteErrorMessage("Installer Path not found: verify that the Plugin Installer has been installed first")
        exit

def ConvertInstallerPathToLicensePath(value: str) -> str:
    result = os.path.dirname(value)
    print('Directory: ' + result)
    result = os.path.join(result, 'plugins.lic')
    print('License Path: ' + result)
    return result

def WriteFileContent(filepath: str, content: str):
    try:
        with open(filepath, 'w') as file:
            file.write(content)
    except:
        WriteErrorMessage('Failed Writing file: make sure that the program is run as admin')

def InstallToPluginInstallerLocation():
    # Requires Elevated Permissions
    installerPath = GetInstallerPath()
    licPath = ConvertInstallerPathToLicensePath(installerPath)
    WriteFileContent(licPath, fileContent)

def InstallToAppData():
    # Does not require Elevated Permissions
    licPath = GetAppDataPath()
    WriteFileContent(licPath, fileContent)

InstallToAppData()