#!/bin/bash

# ============================================
# UPDATER FILES - Nebulauncher Downloader
# ============================================

# Kolory dla UI
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m' # No Color
BG_RED='\033[41m'
BG_GREEN='\033[42m'
BG_BLUE='\033[44m'

# Symbole
CHECK_MARK="✓"
CROSS_MARK="✗"
ARROW="→"
GEAR="⚙️"
CLOUD="☁️"
PACKAGE="📦"
WARNING="⚠️"
INFO="ℹ️"
HOURGLASS="⏳"
STAR="⭐"

# Funkcja czyszczenia ekranu
clear_screen() {
    printf "\033[2J\033[H"
}

# Funkcja rysowania linii
draw_line() {
    printf "${DIM}"
    printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '─'
    printf "${NC}"
}

# Funkcja nagłówka
draw_header() {
    clear_screen
    echo -e "${CYAN}${BOLD}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    ${WHITE}NEBULAUNCHER UPDATER${CYAN}                     ║"
    echo "║                        ${DIM}File Downloader${CYAN}                         ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    draw_line
    echo ""
}

# Funkcja paska postępu
show_progress() {
    local current=$1
    local total=$2
    local width=50
    local percentage=$((current * 100 / total))
    local filled=$((percentage * width / 100))
    local empty=$((width - filled))
    
    printf "\r${YELLOW}[${GREEN}"
    printf "%${filled}s" | tr ' ' '█'
    printf "${DIM}"
    printf "%${empty}s" | tr ' ' '░'
    printf "${YELLOW}] ${WHITE}%3d%%${NC}" "$percentage"
}

# Funkcja animacji ładowania
loading_animation() {
    local pid=$1
    local message=$2
    local spin='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
    local i=0
    
    while kill -0 "$pid" 2>/dev/null; do
        printf "\r${CYAN}${spin:$i:1}${NC} ${DIM}${message}${NC}"
        i=$(((i + 1) % 10))
        sleep 0.1
    done
    printf "\r${GREEN}${CHECK_MARK}${NC} ${DIM}${message} - ${GREEN}Gotowe!${NC}    \n"
}

# Funkcja pobierania z GUI
download_with_gui() {
    local url=$1
    local output=$2
    local name=$3
    
    echo -e "\n${GEAR} ${BOLD}${name}${NC}"
    echo -e "${DIM}${ARROW} Źródło: ${url##*/}${NC}"
    echo -e "${ARROW} Cel: ${output}${NC}"
    echo -e "${HOURGLASS} Rozpoczynam pobieranie...\n"
    
    # Pobieranie z pokazywaniem postępu
    wget -O "$output" "$url" 2>&1 | while read -r line; do
        if [[ $line =~ ([0-9]+)% ]]; then
            percentage=${BASH_REMATCH[1]}
            show_progress "$percentage" 100
        fi
    done
    
    # Sprawdzenie czy się udało
    if [ -f "$output" ] && [ -s "$output" ]; then
        local size=$(du -h "$output" | cut -f1)
        echo -e "\n${GREEN}${CHECK_MARK}${NC} ${GREEN}Pobrano pomyślnie!${NC} ${DIM}(${size})${NC}"
        return 0
    else
        echo -e "\n${RED}${CROSS_MARK}${NC} ${RED}Błąd pobierania!${NC}"
        return 1
    fi
}

# Funkcja menu głównego
show_menu() {
    echo ""
    draw_line
    echo -e "\n${BOLD}${WHITE}📋 DOSTĘPNE OPCJE:${NC}\n"
    echo -e "  ${GREEN}1${NC}) ${CYAN}Pobierz wszystkie pliki${NC}     ${DIM}(zalecane)${NC}"
    echo -e "  ${GREEN}2${NC}) ${CYAN}Pobierz tylko Nebulauncher.exe${NC}"
    echo -e "  ${GREEN}3${NC}) ${CYAN}Pobierz tylko NebulaLauncher-Setup.exe${NC}"
    echo -e "  ${GREEN}4${NC}) ${YELLOW}Sprawdź istniejące pliki${NC}"
    echo -e "  ${GREEN}5${NC}) ${RED}Usuń pobrane pliki${NC}"
    echo -e "  ${GREEN}0${NC}) ${RED}Wyjście${NC}"
    echo ""
    draw_line
    echo -ne "\n${BOLD}${WHITE}${ARROW} Twój wybór: ${NC}"
}

# Funkcja sprawdzania plików
check_files() {
    echo -e "\n${INFO} ${BOLD}Sprawdzam istniejące pliki...${NC}\n"
    
    local files=("Nebulauncher.exe" "NebulaLauncher-Setup.exe")
    
    for file in "${files[@]}"; do
        if [ -f "$file" ]; then
            local size=$(du -h "$file" | cut -f1)
            local perms=$(ls -l "$file" | cut -d' ' -f1)
            echo -e "  ${GREEN}${CHECK_MARK}${NC} ${WHITE}${file}${NC} ${DIM}[${size}, ${perms}]${NC}"
        else
            echo -e "  ${RED}${CROSS_MARK}${NC} ${DIM}${file}${NC} ${DIM}- brak${NC}"
        fi
    done
    echo ""
    draw_line
    echo -e "\n${DIM}Naciśnij Enter aby kontynuować...${NC}"
    read -r
}

# Funkcja usuwania plików
delete_files() {
    echo -e "\n${WARNING} ${YELLOW}${BOLD}UWAGA!${NC} ${YELLOW}Czy na pewno chcesz usunąć wszystkie pobrane pliki?${NC}\n"
    echo -e "  ${DIM}Pliki do usunięcia:${NC}"
    
    local any=false
    for file in "Nebulauncher.exe" "NebulaLauncher-Setup.exe"; do
        if [ -f "$file" ]; then
            echo -e "    ${RED}${CROSS_MARK}${NC} ${file}"
            any=true
        fi
    done
    
    if [ "$any" = false ]; then
        echo -e "    ${DIM}${INFO} Brak plików do usunięcia${NC}"
        echo -e "\n${DIM}Naciśnij Enter...${NC}"
        read -r
        return
    fi
    
    echo ""

    echo -ne "${YELLOW}Potwierdź usuwanie (t/N): ${NC}"
    read -n 1 -r
    echo ""

    if [[ "$REPLY" =~ ^[Tt]$ ]]; then
        rm -f Nebulauncher.exe NebulaLauncher-Setup.exe
        echo -e "\n${GREEN}${CHECK_MARK}${NC} ${GREEN}Pliki zostały usunięte!${NC}"
    else
        echo -e "\n${INFO} Anulowano usuwanie."
    fi

    echo ""
    draw_line
    echo -e "\n${DIM}Naciśnij Enter...${NC}"
    read -r

    echo ""
    if [[ $REPLY =~ ^[Tt]$ ]]; then
        rm -f Nebulauncher.exe NebulaLauncher-Setup.exe
        echo -e "\n${GREEN}${CHECK_MARK}${NC} ${GREEN}Pliki zostały usunięte!${NC}"
    else
        echo -e "\n${INFO} Anulowano usuwanie."
    fi
    echo ""
    draw_line
    echo -e "\n${DIM}Naciśnij Enter...${NC}"
    read -r
}

# Funkcja pobierania wszystkiego
download_all() {
    local failed=0
    
    echo -e "\n${CLOUD} ${BOLD}Rozpoczynam pobieranie...${NC}\n"
    draw_line
    
    # Pobieranie Nebulauncher.exe
    download_with_gui "https://huggingface.co/datasets/qwdqdqwe/system-gier/resolve/main/Nebulauncher.exe" \
                      "Nebulauncher.exe" \
                      "Nebulauncher.exe"
    if [ $? -ne 0 ]; then failed=1; fi
    
    echo ""
    draw_line
    
    # Pobieranie NebulaLauncher-Setup.exe
    download_with_gui "https://huggingface.co/datasets/qwdqdqwe/system-gier/resolve/main/NebulaLauncher-Setup.exe" \
                      "NebulaLauncher-Setup.exe" \
                      "NebulaLauncher-Setup.exe"
    if [ $? -ne 0 ]; then failed=1; fi
    
    echo ""
    draw_line
    
    if [ $failed -eq 0 ]; then
        echo -e "\n${STAR} ${GREEN}${BOLD}WSZYSTKIE PLIKI POBRANE POMYŚLNIE!${NC} ${STAR}\n"
        check_files
    else
        echo -e "\n${WARNING} ${YELLOW}Niektóre pliki mogły nie zostać pobrane poprawnie.${NC}\n"
    fi
    
    echo -e "${DIM}Naciśnij Enter aby kontynuować...${NC}"
    read -r
}

# Główna pętla programu
main() {
    while true; do
        draw_header
        show_menu
        read -r choice
        
        case $choice in
            1)
                download_all
                ;;
            2)
                draw_header
                download_with_gui "https://huggingface.co/datasets/qwdqdqwe/system-gier/resolve/main/Nebulauncher.exe" \
                                  "Nebulauncher.exe" \
                                  "Nebulauncher.exe"
                echo -e "\n${DIM}Naciśnij Enter...${NC}"
                read -r
                ;;
            3)
                draw_header
                download_with_gui "https://huggingface.co/datasets/qwdqdqwe/system-gier/resolve/main/NebulaLauncher-Setup.exe" \
                                  "NebulaLauncher-Setup.exe" \
                                  "NebulaLauncher-Setup.exe"
                echo -e "\n${DIM}Naciśnij Enter...${NC}"
                read -r
                ;;
            4)
                draw_header
                check_files
                ;;
            5)
                draw_header
                delete_files
                ;;
            0)
                clear_screen
                echo -e "\n${GREEN}${BOLD}Do widzenia!${NC}\n"
                exit 0
                ;;
            *)
                echo -e "\n${RED}${CROSS_MARK} Nieprawidłowa opcja!${NC}"
                sleep 1
                ;;
        esac
    done
}

# Sprawdzenie czy wget jest zainstalowany
if ! command -v wget &> /dev/null; then
    echo -e "${RED}${CROSS_MARK} Wget nie jest zainstalowany!${NC}"
    echo -e "${YELLOW}Zainstaluj go: sudo apt install wget${NC}"
    exit 1
fi

# Uruchomienie programu
main
