#!/usr/bin/python3
# PROTON CONFIG

import os
import shutil
import sys
import json
from urllib import request

HOME = os.path.expanduser("~")
STEAM_PATH = HOME + "/.steam/steam/steamapps/common/"
IS_FLATPAK = False

ARGS = sys.argv[1:]

VERSION = "0.2.1"


class Style:
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    END = '\033[0m'


def help():
    print("""
Usage: proton-config <SUBCOMMAND> [VALUE]

Avaliable subcommands:
    rpc-enable <yes/no> - Enable support for Discord Rich Persence
    rpc-path   <PATH>   - Set PATH for exe to handle IPC Discord Rich Persence
    version             - Show current version
    path       <PATH>   - Set Proton PATH
    prefix     <PATH>   - Set Proton's prefix PATH
    list                - Show list of Proton installed
    show                - Show the contents in config.json
    uninstall           - Uninstall Proton CLI helper
    explorer            - Open driver C: in external file manager
""")

def steam_source():
    global STEAM_PATH
    global IS_FLATPAK
    steam_system_path = HOME + "/.local/share/Steam/"
    steam_flatpak_path = HOME + "/.var/app/com.valvesoftware.Steam/.local/share/Steam/"
    steam_flatpak_apps_path = steam_flatpak_path + "steamapps/common/"
    if os.path.isdir(steam_flatpak_path) and os.path.isdir(steam_system_path):
        print("You have steam client installed on both system and flatpak!")
        print("Which steam client do you want to use for?")
        confirm = ask("Y - choose for system, N - choose for flatpak")
        if not confirm:
            STEAM_PATH = steam_flatpak_apps_path
            IS_FLATPAK = True
            print("Chosen flatpak!")
        else:
            print("Chosen system!")
    elif not os.path.isdir(steam_system_path):
        STEAM_PATH = steam_flatpak_apps_path
        IS_FLATPAK = True
    elif not os.path.isdir(steam_system_path) and not os.path.isdir(steam_flatpak_path):
        print("You don't have Steam client installed! Please install first.")
        sys.exit(1)


def get_config():
    with open(HOME + "/.config/proton-cli/config.json") as f:
        j = json.load(f)
        f.close()
        return j


def ask(question: str) -> bool:
    i = input(question + " [Y/N] ")
    return i.lower() in ["yes", "y"]


def create_local_if_not_exists():
    local_path = HOME + "/.local/share/proton-cli"
    if not os.path.isdir(local_path):
        os.makedirs(local_path)
    if not os.path.isdir(local_path + "/proton"):
        os.makedirs(local_path + "/proton")


def boolean(value: str) -> bool:
    if value.lower() in ["yes", "true", "y"]:
        return True
    elif value.lower() in ["no", "false", "n"]:
        return False
    else:
        help()
        sys.exit(1)

def proton_sources():
    steam_source()
    global IS_FLATPAK
    steam_arr = [{"name": l, "path": STEAM_PATH} for l in os.listdir(STEAM_PATH) if "proton" in l.lower()]
    if IS_FLATPAK:
        steam_compartibility_path = HOME + "/.var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d/"
    else:
        steam_compartibility_path = HOME + "/.local/share/Steam/compatibilitytools.d/"
    comp_arr = [{"name": l, "path": steam_compartibility_path} for l in os.listdir(steam_compartibility_path) if "proton" in l.lower()]
    return steam_arr + comp_arr


def main():
    if ARGS[0] == "rpc-enable":
        if not ARGS[1]:
            help()
            return
        else:
            config = get_config()
            arg = boolean(ARGS[1])
            local_path = HOME + "/.local/share/proton-cli"
            exe = os.path.join(local_path, "winediscordipcbridge.exe")
            if arg is True and not os.path.isfile(exe):
                create_local_if_not_exists()
                print("Downloading winediscordipcbridge.exe...")
                request.urlretrieve(
                    "https://github.com/0e4ef622/wine-discord-ipc-bridge/releases/download/v0.0.2/winediscordipcbridge.exe", exe)
                print("Downloaded!")
                config["RPC"]["path"] = exe
            with open(HOME + "/.config/proton-cli/config.json", "w") as f:
                config["RPC"]["enable"] = arg
                json.dump(config, f)
                f.close()
            print('RPC support enabled!' if arg else "RPC support disabled!")

    elif ARGS[0] == "rpc-path":
        if not ARGS[1]:
            help()
            return
        else:
            config = get_config()
            with open(HOME + "/.config/proton-cli/config.json", "w") as f:
                config["RPC"]["path"] = " ".join(ARGS[1:])
                json.dump(config, f)
                f.close()
            print("RPC exe path has been changed!")

    elif ARGS[0] == "version":
        local_path = HOME + "/.local/share/proton-cli"
        ver = os.path.join(local_path, "version")
        if os.path.exists(ver):
            with open(ver) as f:
                commit = f.read()
                f.close()
                print(f"Version {VERSION} (Commit: {commit})")
        else:
            print(f"Version {VERSION}")
    
    elif ARGS[0] == "prefix":
        if not ARGS[1]:
            help()
            return
        else:
            config = get_config()
            with open(HOME + "/.config/proton-cli/config.json", "w") as f:
                config["PROTON_PREFIX"] = " ".join(ARGS[1:])
                json.dump(config, f)
                f.close()

    elif ARGS[0] == "path":
        if not ARGS[1]:
            help()
            return
        else:
            config = get_config()
            with open(HOME + "/.config/proton-cli/config.json", "w") as f:
                config["PROTON_PATH"] = " ".join(ARGS[1:])
                json.dump(config, f)
                f.close()

    elif ARGS[0] == "list":
        dirs = proton_sources()
        print("\n".join([f"{Style.BOLD}{i['name']}{Style.END} from {i['path']}" for i in dirs]))

    elif ARGS[0] == "show":
        config = get_config()
        print(f"{HOME}/.config/proton-cli/config.json")
        print(json.dumps(config, indent=2, sort_keys=True))

    elif ARGS[0] == "uninstall":
        confirm = ask(
            "Are you sure you want to remove the helper?\nThis will remove commands we copied.")
        if not confirm:
            print("Cancelled")
            return
        else:
            print("Ok, processing...")

            for file in ["proton-cli", "proton-config"]:
                try:
                    os.remove(os.path.join(HOME, ".local", "bin", file))
                except:
                    continue
            confi = ask("Do you also want to remove all data?\nTHIS ALSO INCLUDES SAVED DATA IN GAMES IF YOU HAVE USED IT.\n(Please backup from ~/.local/share/proton-cli/proton if you want to remove)")
            if not confi:
                print("Ok I will keep all data. Sucessfully uninstalled!")
            else:
                config_path = HOME + "/.config/proton-cli"
                local_path = HOME + "/.local/share/proton-cli"
                shutil.rmtree(local_path)
                shutil.rmtree(config_path)
                print("Sucessfully uninstalled and deleted all data!")
    elif ARGS[0] == "explorer":
        local_path = HOME + "/.local/share/proton-cli/proton/pfx/drive_c"
        os.system(f"xdg-open file:///{local_path}")

    else:
        help()
        return


if __name__ == "__main__":
    try:
        main()
    except IndexError:
        help()
