#!/bin/bash

APP_STORE_DIRECTORY="apps"
CATEGORIES_FILE="etc/categories"
THEMES_DIRECTORY="/usr/share/themes"
THEMES_FILE="etc/theme"

show_settings() {
    chmod +x theme
    pkill -f "yad.*"
    themes+="System Default"
    while IFS= read -r -d '' theme; do
        # Extract just the name of the theme directory from its full path
        theme_name=$(basename "$theme")
        themes+=("$theme_name")
    done < <(find "$THEMES_DIRECTORY" -maxdepth 1 -mindepth 1 -type d -print0 | sort -z)
    theme_string=""
    for theme in "${themes[@]}"; do
        if [ -n "$theme_string" ]; then
            theme_string+="!"
        fi
        theme_string+="$theme"
    done

    texteditors=("System Default!Visual Studio Code!Geany!Gedit!Mousepad!VSCodium")

    # I don't know why these are around this way, and why they only work that way.
    settings=$(yad --form \
        --title="Settings" --columns=1 --output-by-row \
        --width="150" --height="400" --center --on-top --borders=20 \
        --field="Theme":CB "$theme_string" \
        --field="Text Editor":CB "$texteditors" \
        --field="<b>Create App</b>"!gtk-new!"Create an app for LinStore and Pi-Apps!":FBTN "./createapp create" \
        --field="<b>Import App</b>"!gtk-open!"Import an app not available in the repository":FBTN "./createapp import" \
        --button="<b>OK</b>!gtk-ok":0 \
        --button="<b>Cancel</b>!gtk-cancel":1)

    # Extracting the selected text editor value from settings
    selected_text_editor=$(echo "$settings" | awk -F '|' '{print $2}')

    # Echoing to the 'etc/editor' file based on the selected text editor
    case "$selected_text_editor" in
    "System Default") echo "xdg-open" >"etc/editor" ;;
    "Visual Studio Code") echo "code" >"etc/editor" ;;
    "Geany") echo "geany" >"etc/editor" ;;
    "Gedit") echo "gedit" >"etc/editor" ;;
    "Mousepad") echo "mousepad" >"etc/editor" ;;
    "VSCodium") echo "codium" >"etc/editor" ;;
    *) echo "$selected_text_editor" >"etc/editor" ;;
    esac

    yad_ret=$?

    if [[ $yad_ret -eq 0 ]]; then
        selected_theme="${settings%%|*}"

        if [[ "$selected_theme" == "System Default" ]]; then
            selected_theme_path=" "
            echo "$selected_theme_path" >"$THEMES_FILE"
        else
            selected_theme_path=$(find "$THEMES_DIRECTORY" -maxdepth 1 -mindepth 1 -type d -name "$selected_theme" -exec basename {} \; -quit)
            echo "$selected_theme_path" >"$THEMES_FILE"
        fi
            
        ./gui
    elif [[ $yad_ret -eq 252 ]]; then
        ./gui
    elif [[ $yad_ret -eq 1 ]]; then
        ./gui
    fi
}

show_settings >/dev/null
