import os
import subprocess
import platform
import urllib.request
import zipfile
import tarfile
import tkinter as tk
from tkinter import messagebox

# Uncomment if using a logo
# from PIL import Image, ImageTk

# -----------------------------
# Functions
# -----------------------------
def write_env(values):
    """Write environment variables to .env file"""
    try:
        with open(".env", "w") as f:
            for key, val in values.items():
                f.write(f"{key}={val}\n")
        print("[INFO] .env file created.")
        messagebox.showinfo("Success", ".env file created!")
    except Exception as e:
        print(f"[ERROR] Failed to write .env: {e}")
        messagebox.showerror("Error", f"Failed to write .env: {e}")

def install_node_windows():
    """Download and extract Node.js for Windows"""
    try:
        print("[INFO] Downloading Node.js for Windows...")
        messagebox.showinfo("Node.js", "Downloading Node.js for Windows...")
        node_url = "https://nodejs.org/dist/v20.5.1/node-v20.5.1-x64.zip"
        node_zip = "node.zip"
        urllib.request.urlretrieve(node_url, node_zip)
        with zipfile.ZipFile(node_zip, 'r') as zip_ref:
            zip_ref.extractall("C:/Nodejs")
        os.remove(node_zip)
        os.environ["PATH"] += os.pathsep + "C:/Nodejs/node-v20.5.1-x64"
        print("[INFO] Node.js installed on Windows.")
        messagebox.showinfo("Node.js", "Node.js installed on Windows!")
    except Exception as e:
        print(f"[ERROR] Failed to install Node.js on Windows: {e}")
        messagebox.showerror("Error", f"Failed to install Node.js on Windows: {e}")

def install_node_linux():
    """Download and extract Node.js for Linux to home directory (safe path)"""
    try:
        print("[INFO] Installing Node.js for Linux...")
        messagebox.showinfo("Node.js", "Installing Node.js for Linux...")
        node_url = "https://nodejs.org/dist/v20.5.1/node-v20.5.1-linux-x64.tar.xz"
        node_tar = "node.tar.xz"
        urllib.request.urlretrieve(node_url, node_tar)
        extract_path = os.path.expanduser("~/nodejs")
        os.makedirs(extract_path, exist_ok=True)
        with tarfile.open(node_tar, "r:xz") as tar:
            tar.extractall(extract_path)
        os.remove(node_tar)
        node_bin_path = os.path.join(extract_path, "node-v20.5.1-linux-x64", "bin")
        os.environ["PATH"] += os.pathsep + node_bin_path
        print(f"[INFO] Node.js installed at {node_bin_path}")
        messagebox.showinfo("Node.js", f"Node.js installed at {node_bin_path}")
    except Exception as e:
        print(f"[ERROR] Failed to install Node.js on Linux: {e}")
        messagebox.showerror("Error", f"Failed to install Node.js on Linux: {e}")

def check_and_install_node():
    """Check if Node.js is installed; install if missing"""
    try:
        result = subprocess.run(["node", "-v"], check=True, capture_output=True, text=True)
        print(f"[INFO] Node.js is already installed: {result.stdout.strip()}")
        messagebox.showinfo("Node.js", f"Node.js is already installed: {result.stdout.strip()}")
    except (subprocess.CalledProcessError, FileNotFoundError):
        system = platform.system()
        print(f"[INFO] Node.js not found. OS detected: {system}")
        if system == "Windows":
            install_node_windows()
        elif system in ("Linux", "Darwin"):
            install_node_linux()
        else:
            print(f"[WARNING] Unsupported OS: {system}. Please install Node.js manually.")
            messagebox.showwarning("Node.js", f"Unsupported OS: {system}. Please install Node.js manually.")

def install():
    """Main install logic"""
    values = {
        "PORT": entry_port.get(),
        "SDC_URL": entry_sdc.get(),
        "PIN": entry_pin.get(),
        "CERT_PATH": entry_cert_path.get(),
        "CERT_PASSWORD": entry_cert_password.get()
    }

    print("[INFO] Starting installation process...")
    write_env(values)
    check_and_install_node()
    print("[INFO] Installation process completed.")
    messagebox.showinfo("Installer", "Installation completed successfully!")

# -----------------------------
# Tkinter UI
# -----------------------------
root = tk.Tk()
root.title("CYBEX ERP - POS Installer")

# -----------------------------
# Optional Logo (commented out)
# -----------------------------
# To use a logo, uncomment and provide the path to your image file
# logo_path = "path/to/logo.png"
# logo_img = Image.open(logo_path)
# logo_img = logo_img.resize((100, 100))  # Resize as needed
# logo_photo = ImageTk.PhotoImage(logo_img)
# logo_label = tk.Label(root, image=logo_photo)
# logo_label.grid(row=0, column=0, columnspan=2, pady=(10, 0))

# Title at the top
title_label = tk.Label(root, text="CYBEX ERP", font=("Helvetica", 18, "bold"))
title_label.grid(row=1, column=0, columnspan=2, pady=(10, 0))

# Subtitle
subtitle_label = tk.Label(root, text="POS Installation", font=("Helvetica", 14))
subtitle_label.grid(row=2, column=0, columnspan=2, pady=(0, 10))

# Labels and entries start below the subtitle/logo
tk.Label(root, text="PORT:").grid(row=3, column=0, sticky="e", padx=5, pady=5)
entry_port = tk.Entry(root)
entry_port.insert(0, "3000")
entry_port.grid(row=3, column=1, padx=5, pady=5)

tk.Label(root, text="SDC_URL:").grid(row=4, column=0, sticky="e", padx=5, pady=5)
entry_sdc = tk.Entry(root)
entry_sdc.grid(row=4, column=1, padx=5, pady=5)

tk.Label(root, text="PIN:").grid(row=5, column=0, sticky="e", padx=5, pady=5)
entry_pin = tk.Entry(root)
entry_pin.grid(row=5, column=1, padx=5, pady=5)

tk.Label(root, text="CERT_PATH:").grid(row=6, column=0, sticky="e", padx=5, pady=5)
entry_cert_path = tk.Entry(root)
entry_cert_path.grid(row=6, column=1, padx=5, pady=5)

tk.Label(root, text="CERT_PASSWORD:").grid(row=7, column=0, sticky="e", padx=5, pady=5)
entry_cert_password = tk.Entry(root, show="*")
entry_cert_password.grid(row=7, column=1, padx=5, pady=5)

# Install button
install_button = tk.Button(root, text="Install", command=install)
install_button.grid(row=8, column=0, columnspan=2, pady=15)

root.mainloop()
