#!/usr/bin/env bash

wineqgui-launch()
{
    local configdir
    local selection
    local file
    local name
    local exe
    local prefix
    local wine_cmd
    local args
    local gamemode
    local entries=()

    configdir="${HOME}/.local/share/wineqgui/applications"

    mkdir -p "$configdir"

    # -------------------------------------------------
    # Finn registrerte applikasjonar
    # -------------------------------------------------

    while IFS= read -r -d '' file; do

        name=$(read_config_value "$file" "NAME")

        [[ -z "$name" ]] && continue

        entries+=("$name" "$file")

    done < <(
        find "$configdir" \
            -maxdepth 1 \
            -type f \
            -name '*.conf' \
            -print0
    )


    # -------------------------------------------------
    # Ingen program registrert
    # -------------------------------------------------

    if (( ${#entries[@]} == 0 )); then

        show_info \
            "No Wine applications have been configured yet."

        return
    fi


    # -------------------------------------------------
    # Vel program
    # -------------------------------------------------

    selection=$(
        qarma --list \
            --title="Launch Wine application" \
            --width=600 \
            --height=400 \
            --hide-header \
            --column="Application" \
            --column="Config" \
            "${entries[@]}"
    )

    [[ -z "$selection" ]] && return


    # -------------------------------------------------
    # Les config
    # -------------------------------------------------

    name=$(read_config_value "$selection" "NAME")
    exe=$(read_config_value "$selection" "EXE")
    prefix=$(read_config_value "$selection" "PREFIX")
    wine_cmd=$(read_config_value "$selection" "WINE")
    args=$(read_config_value "$selection" "ARGS")
    gamemode=$(read_config_value "$selection" "GAMEMODE")


    # -------------------------------------------------
    # Kontroller
    # -------------------------------------------------

    if [[ ! -f "$exe" ]]; then

        show_error \
            "Executable does not exist:\n\n<b>${exe}</b>"

        return 1
    fi


    if [[ ! -d "$prefix" ]]; then

        show_error \
            "Wine environment does not exist:\n\n<b>${prefix}</b>"

        return 1
    fi


    # -------------------------------------------------
    # Start programmet
    # -------------------------------------------------

    export WINEPREFIX="$prefix"

    if [[ "$gamemode" == "1" ]] &&
       command -v gamemoderun >/dev/null 2>&1
    then

        gamemoderun "$wine_cmd" "$exe" $args &

    else

        "$wine_cmd" "$exe" $args &

    fi
}
