import os
import json
import configparser
from os.path import isdir, join
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtGui import QIcon

def populate_accounts_java(account_selector: QComboBox, splitscreen_selector: QComboBox, accounts_path: str):
    account_selector.clear()
    splitscreen_selector.clear()

    if not accounts_path or not os.path.exists(accounts_path):
        account_selector.addItem("No accounts found")
        return

    with open(accounts_path) as f:
        accounts = json.load(f)

    profile_names = [
        account.get("profile", {}).get("name")
        for account in accounts.get("accounts", [])
        if "name" in account.get("profile", {})
    ]

    account_selector.addItems(profile_names)
    splitscreen_selector.addItems(profile_names)

def populate_versions_java(version_selector: QComboBox, instances_path: str, default_icon_path="./assets/icons/game/mcje.png"):
    version_selector.clear()

    if not instances_path or not os.path.exists(instances_path):
        version_selector.addItem("No instances found")
        return

    default_icon = QIcon(default_icon_path)
    versions = sorted(
        f for f in os.listdir(instances_path)
        if isdir(join(instances_path, f)) and not f.startswith(".")
    )

    if not versions:
        version_selector.addItem("No instances found")
        return

    for v in versions:
        vp = join(instances_path, v)
        for folder in ("minecraft", ".minecraft"):
            icon_file = join(vp, folder, "icon.png")
            if os.path.exists(icon_file):
                break
        else:
            icon_file = None
        version_selector.addItem(QIcon(icon_file) if icon_file else default_icon, v)

def populate_versions_bedrock(version_selector: QComboBox):
    version_selector.clear()

    flatpak = os.path.expanduser("~/.var/app/io.mrarm.mcpelauncher/data/mcpelauncher/profiles/profiles.ini")
    native = os.path.expanduser("~/.local/share/mcpelauncher/profiles/profiles.ini")
    ini_path = flatpak if os.path.exists(flatpak) else native if os.path.exists(native) else None

    if not ini_path:
        version_selector.addItem("No profiles.ini found")
        return

    ini = configparser.ConfigParser()
    ini.read(ini_path)
    profiles = [s for s in ini.sections() if s != "General"]

    icon = QIcon("./assets/icons/game/mcbe.png")

    if not profiles:
        version_selector.addItem("No profiles found")
    else:
        for p in profiles:
            version_selector.addItem(icon, p.replace('%20', ' '))
