#!/bin/bash

APP_STORE_NAME="LinStore"
APP_STORE_WIDTH=320
APP_STORE_HEIGHT=600
pwd
if ! command -v yad &>/dev/null; then
    error "YAD needs to be installed to run LinStore."
fi
if [ -f "gui" ] || [ -f "createapp" ] || [ -f "settings" ]; then
    cd .
else
    cd ~/.linstore
fi

resolution=$(xrandr | grep " connected primary" | awk '{print $4}' | cut -d'+' -f1)

horizontal=$(echo $resolution | cut -d'x' -f1)
vertical=$(echo $resolution | cut -d'x' -f2)
let "categoryPos=$horizontal/2-360"
let "categoryPosY=$vertical/2-340"

declare -A categories
declare -A category_apps

detect_and_write_architecture() {
    mkdir -p ~/.linstore
    case "$(uname -m)" in
    x86_64)
        echo "x64" >~/.linstore/architecture.txt
        ;;
    i686)
        echo "x86" >~/.linstore/architecture.txt
        ;;
    armv7l)
        echo "32" >~/.linstore/architecture.txt
        ;;
    aarch64)
        echo "64" >~/.linstore/architecture.txt
        ;;
    *)
        echo "Unknown architecture" >~/.linstore/architecture.txt
        ;;
    esac
}

read_categories() {
    while read -r category; do
        categories["$category"]=""
    done <etc/categories

    for app_dir in apps/*; do
        app_name=$(basename "$app_dir")
        category_file="apps/$app_name/category"
        install_script="$app_dir/install"

        # Check if the install script or architecture-specific install scripts exist for this app
        if [ -e "$install_script" ]; then
            while IFS= read -r app_in_category; do
                if [ -n "${categories[$app_in_category]}" ]; then
                    categories["$app_in_category"]+=" $app_name"
                    category_apps["$app_in_category"]+="|$app_name"
                else
                    categories["$app_in_category"]="$app_name"
                    category_apps["$app_in_category"]="$app_name"
                fi
            done <"$category_file"
        else
            architecture=$(cat ~/.linstore/architecture.txt)
            install_script_arch="install-$architecture"

            if [ -e "$app_dir/$install_script_arch" ]; then
                while IFS= read -r app_in_category; do
                    if [ -n "${categories[$app_in_category]}" ]; then
                        categories["$app_in_category"]+=" $app_name"
                        category_apps["$app_in_category"]+="|$app_name"
                    else
                        categories["$app_in_category"]="$app_name"
                        category_apps["$app_in_category"]="$app_name"
                    fi
                done <"$category_file"
            fi
        fi
    done
}

get_app_description() {
    app_name="$1"
    description_file="apps/$app_name/description"
    if [ -e "$description_file" ]; then
        cat "$description_file"
    else
        echo "No description available."
    fi
}

get_app_creator() {
    app_name="$1"
    creator_file="apps/$app_name/creator"
    if [ -e "$creator_file" ]; then
        cat "$creator_file"
    else
        echo "No description available."
    fi
}

get_app_website() {
    app_name="$1"
    website_file="apps/$app_name/website"
    if [ -e "$website_file" ]; then
        cat "$website_file"
    else
        echo "No description available."
    fi
}
theme_get() {
    website_file="etc/theme"
    if [ -e "$website_file" ]; then
        cat "$website_file"
    else
        echo ""
    fi
}
theme=$(theme_get)

app_details_page() {
    sleep 0.1
    pos=$(wmctrl -lG | grep "Category" | awk '{print $3,$4}')
    x2=$((horizontal / 2 - 40))
    y2=$((vertical / 2 - 340))
    
    if [ -e "$HOME/.linstore/installscripts/${1//|/}" ]; then
        installed="true"
    else
        installed="false"
    fi

    TITLE="App Details"
    wmctrl -l | grep "$TITLE" | awk '{print $1}' | while read -r window_id; do
        wmctrl -ic "$window_id"
    done

    local selected_app_name="${1//|/}"
    local app_directory="apps/$selected_app_name"
    local app_icon="$app_directory/icon-48.png"
    local description=$(get_app_description "$selected_app_name")
    local creator=$(get_app_creator "$selected_app_name")
    local website=$(get_app_website "$selected_app_name")

    local install_command=$(./api install "$app_directory" "$selected_app_name")
    local uninstall_command=$(./api uninstall "$app_directory" "$selected_app_name")

    if [[ "$installed" == "true" ]]; then
        buttonText="Uninstall"
        buttonImage="images/button/uninstall.png"
        # Create a temporary script for the commands
        temp_script=$(mktemp)
        echo "$uninstall_command && rm -rf \"$HOME/.linstore/installscripts/$selected_app_name\"" > "$temp_script"
        chmod +x "$temp_script"
        buttonCommand="bash -c 'bash $temp_script; rm $temp_script'"
    else
        buttonText="Install"
        buttonImage="images/button/install.png"
        buttonCommand="$install_command"
    fi

    (
        yad --class LinStore --title="App Details" --geometry=450x${APP_STORE_HEIGHT}+${x2}+${y2} --form \
            --text "<big><b>${selected_app_name}</b></big>\n<b>${creator}</b>\n<b><a href='${website}'>${website}</a></b>\n" \
            --field="<b>Description</b>:TXT" --no-edit "$description" --image="$app_icon" --window-icon="images/logo/logo-64.png" --image-on-top \
            --button="$buttonText!$buttonImage:$buttonCommand" --skip-taskbar
    )

    rm -f /tmp/description.tmp
    kill $(pgrep -f "title=App Details")
}

show_categories() {
    list_items=()
    for category in "${!categories[@]}"; do
        category_icon="images/$category.png"
        list_items+=("$category_icon")
        list_items+=("$category")
    done

    selected_category_raw=$(GTK_THEME="${theme}" yad --text "Welcome to LinStore\nThe app store that's simple to use." --width="$APP_STORE_WIDTH" --height="$APP_STORE_HEIGHT" --columns="2" \
        "${list_items[@]}" \
        --list --image="images/logo-64.png" --window-icon="images/logo/logo-64.png" --image-on-top --title "$APP_STORE_NAME" --column "Icon:IMG" --column "Category" --button "Show Apps:3" --button "Settings:4" --item-padding="10")

    selected_category="${selected_category_raw//|/}"
    echo "$selected_category"
}

show_apps_in_category() {
    while true; do
        if [ "$1" == "All Apps" ]; then
            # Show all apps in the "All Apps" category
            all_apps_list=()
            for app_dir in apps/*; do
                app_name=$(basename "$app_dir")
                app_icon="apps/$app_name/icon-24.png"
                all_apps_list+=("$app_icon")
                all_apps_list+=("$app_name")
            done

            GTK_THEME="${theme}" yad --text "<big><b>$1</b></big>" --geometry=${APP_STORE_WIDTH}x${APP_STORE_HEIGHT}+${categoryPos}+${categoryPosY} --center --columns="2" \
                --list --image="images/logo/logo-64.png" --window-icon="images/logo/logo-64.png" --image-on-top --title "All Apps Category" --column "Icon:IMG" --column "Apps" \
                --button="Back"!images/button/back.png!:4 --separator="\n" "${all_apps_list[@]}" --no-headers \
                --dclick-action='bash -c "./gui showdetails \"%s\""'
        else
            apps_in_category="${category_apps["$1"]}"
            formatted_apps=()

            IFS='|' read -r -a app_list <<<"$apps_in_category"
            for app in "${app_list[@]}"; do
                app_icon="apps/$app/icon-24.png"
                formatted_apps+=("$app_icon")
                formatted_apps+=("$app")
            done

            GTK_THEME="${theme}" yad --text "<big><b>Apps in $1 Category</b></big>" --geometry=${APP_STORE_WIDTH}x${APP_STORE_HEIGHT}+${categoryPos}+${categoryPosY} --center --columns="2" \
                --list --image="images/logo/logo-64.png" --window-icon="images/logo/logo-64.png" --image-on-top --title "$1 Category" --column "Icon:IMG" --column "Apps" \
                --button="Back"!images/button/back.png!:4 --separator="\n" "${formatted_apps[@]}" --no-headers \
                --dclick-action='bash -c "./gui showdetails \"%s\""'
        fi

        button_clicked=$?
        if [ $button_clicked -eq 4 ]; then
            show_app_store
            break
        fi

        show_app_store
        break
    done
}

show_app_store() {
    read_categories

    # Sort categories alphabetically and format with newlines
    sorted_categories=$(printf '%s\n' "${!categories[@]}" | sort)

    list_items=()
    list_items=("images/categories/All Apps.png" "All Apps")
    while IFS= read -r category; do
        category_icon="images/categories/$category.png" # Path to category icons
        list_items+=("$category_icon")
        list_items+=("$category")
    done <<<"$sorted_categories"

    # Fetching a random line from the announcements file
    random_announcement=$(shuf -n 1 etc/announcements)

    # Search function

    selected_category_raw=$(GTK_THEME="${theme}" yad --text "$random_announcement" --geometry=${APP_STORE_WIDTH}x${APP_STORE_HEIGHT}+${categoryPos}+${categoryPosY} --center --columns="3" \
        "${list_items[@]}" \
        --list --image="images/logo/logo-64.png" --window-icon="images/logo/logo-64.png" --image-on-top --title "$APP_STORE_NAME" --column "Icon:IMG" --column "Category" --button "!images/button/search.png"!"Search":"bash -c './api search'" --button "!images/button/update.png"!"Updates":"bash -c './update'" --button "!images/button/settings.png"!"Settings":"bash -c './settings'" --no-headers --item-height="$welcome_height" --timeout=0 --no-close)
    exval=$?
    echo $exval
    selected_category="${selected_category_raw//|/}"

    if [ "$exval" == "44" ]; then
        ./api search && show_app_store
    elif [ -n "$selected_category" ]; then
        show_apps_in_category "$selected_category"
    elif [ "$exval" -eq "252" ]; then
        pkill -f "yad*"
    fi
}

if [[ $1 == "showdetails" ]]; then
    app_details_page "$(echo $2 | awk -F"'" '{print $4}')"
else
    detect_and_write_architecture
    show_app_store
fi