import tkinter as tk
from tkinter import messagebox, ttk
import subprocess
import sys
import os
import threading

class VoshaUninstaller:
    def __init__(self, root):
        self.root = root
        self.root.title("VOSHA Framework Uninstaller v1.0")
        self.root.geometry("600x450")
        self.root.configure(bg="#fff5f5") # Light red/pinkish background for uninstalling
        self.root.resizable(False, False)

        # Style context
        self.primary_color = "#ff4757" # Danger red color
        self.bg_color = "#fff5f5"
        self.text_color = "#2d3436"

        self.setup_ui()

    def setup_ui(self):
        # Header
        header_frame = tk.Frame(self.root, bg="white", height=80)
        header_frame.pack(fill="x")
        header_frame.pack_propagate(False)

        try:
            # Try to load logo
            logo_path = os.path.join(os.path.dirname(__file__), "vosha_framework", "logo.png")
            if not os.path.exists(logo_path):
                 logo_path = "logo.png" # Fallback
            
            temp_img = tk.PhotoImage(file=logo_path)
            # Scale down if too large (subsample)
            width = temp_img.width()
            height = temp_img.height()
            scale = max(width // 60, height // 60) if (width > 60 or height > 60) else 1
            self.logo_img = temp_img.subsample(scale, scale)
            
            logo_label = tk.Label(header_frame, image=self.logo_img, bg="white")
            logo_label.pack(side="left", padx=20)
        except Exception:
            pass

        tk.Label(header_frame, text="VOSHA", font=("Poppins", 18, "bold"), bg="white", fg="#004aad").pack(side="left")
        tk.Label(header_frame, text="Uninstaller", font=("Poppins", 14), bg="white", fg=self.primary_color).pack(side="left", padx=5)

        # Content
        content_frame = tk.Frame(self.root, bg=self.bg_color, padx=40, pady=20)
        content_frame.pack(fill="both", expand=True)

        tk.Label(content_frame, text="Menghapus VOSHA Framework?", font=("Poppins", 16, "bold"), bg=self.bg_color, fg=self.text_color).pack(anchor="w")
        tk.Label(content_frame, text="Seluruh komponen framework akan dihapus dari sistem ini.", font=("Poppins", 10), bg=self.bg_color, fg="#636e72").pack(anchor="w", pady=(0, 15))

        # Progress bar
        self.progress = ttk.Progressbar(content_frame, orient="horizontal", length=520, mode="determinate")
        self.progress.pack(pady=5)

        # Status Log
        tk.Label(content_frame, text="Status Penghapusan:", font=("Poppins", 9, "bold"), bg=self.bg_color, fg=self.text_color).pack(anchor="w")
        self.log_text = tk.Text(content_frame, height=9, bg="#ffffff", font=("Courier New", 9), relief="flat", padx=10, pady=10)
        self.log_text.pack(fill="x", pady=(5, 15))
        self.log_text.insert("1.0", "Siap untuk menghapus VOSHA...\n")
        self.log_text.config(state="disabled")

        # Footer Buttons
        footer_frame = tk.Frame(self.root, bg=self.bg_color, pady=10)
        footer_frame.pack(fill="x")

        self.btn_action = tk.Button(footer_frame, text="HAPUS SEKARANG", bg=self.primary_color, fg="white", 
                                font=("Poppins", 10, "bold"), padx=40, pady=10, relief="flat", cursor="hand2",
                                command=self.confirm_uninstall)
        self.btn_action.pack()

    def update_log(self, message):
        self.log_text.config(state="normal")
        self.log_text.insert("end", f"> {message}\n")
        self.log_text.see("end")
        self.log_text.config(state="disabled")
        self.root.update_idletasks()

    def confirm_uninstall(self):
        if messagebox.askyesno("Konfirmasi", "Apakah Anda yakin ingin menghapus VOSHA Framework?"):
            self.start_uninstall()

    def start_uninstall(self):
        self.btn_action.config(state="disabled", text="Menghapus...")
        self.progress["value"] = 10
        threading.Thread(target=self.run_uninstall, daemon=True).start()

    def run_uninstall(self):
        try:
            self.update_log("Memulai proses penghapusan...")
            is_linux = sys.platform.startswith("linux")
            
            # Step 1: PIP Uninstall
            cmd = [sys.executable, "-m", "pip", "uninstall", "vosha", "-y"]
            self.update_log("Menghapus package 'vosha' via PIP...")
            self.progress["value"] = 40
            
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
            for line in process.stdout:
                self.update_log(line.strip())
            process.wait()

            # Step 2: Clean up shortcuts/configs if needed
            if is_linux:
                shortcut = os.path.expanduser("~/.local/bin/vosha")
                if os.path.exists(shortcut):
                    self.update_log(f"Menghapus shortcut: {shortcut}")
                    os.remove(shortcut)
            
            self.progress["value"] = 100
            self.update_log("PENGHAPUSAN BERHASIL!")
            messagebox.showinfo("Sukses", "VOSHA Framework telah berhasil dihapus dari sistem.")
            self.btn_action.config(text="Keluar", state="normal", command=self.root.quit)
                
        except Exception as e:
            self.update_log(f"Error: {str(e)}")
            messagebox.showerror("Error", f"Terjadi kesalahan: {str(e)}")
            self.btn_action.config(text="Coba Lagi", state="normal")

if __name__ == "__main__":
    root = tk.Tk()
    app = VoshaUninstaller(root)
    root.mainloop()
