#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import urllib.request
import gi
import subprocess
import getpass
from pathlib import Path

gi.require_version('Gtk', '3.0')
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import Gtk, GLib, GdkPixbuf

from hga.controlgrupos.common.srunningcontrol import SRunningControl
from hga.controlgrupos.servidor.settingsservidor import PID_FILE_SERVER
from hga.controlgrupos.servidor.settingsservidor import GUI_SERVIDOR
from hga.appcore import AppCore

# ======================================================
# Rutas
# ======================================================
SCRIPT_ETHERPAD = "/usr/bin/sar-hgr-edit_settings_etherpad.sh"
SCRIPT_ETHERPAD_PROPIETARIO = "/usr/bin/sar-hgr-permisos.sh"
ICONO_CONEXION = "/usr/lib/python3/dist-packages/hga/gui/common/icon/error_conexion.png"

# ======================================================
# Ruta de certificados dinámica por usuario
# ======================================================
def obtener_ruta_certificados():
    """
    Devuelve la ruta correcta para los certificados TLS
    dentro del HOME del usuario real (no de root).
    """
    try:
        # Obtener usuario real que ejecuta el entorno gráfico
        usuario = os.getenv("SUDO_USER") or os.getenv("USER") or getpass.getuser()
        home_usuario = Path(f"/home/{usuario}").expanduser()
        if not home_usuario.exists():
            # fallback si el usuario no tiene /home clásico (por ejemplo root)
            home_usuario = Path.home()
        cert_dir = home_usuario / ".local/share/gnome-remote-desktop"
        return cert_dir
    except Exception:
        # Si algo falla, usar HOME del proceso actual
        return Path.home() / ".local/share/gnome-remote-desktop"

CERT_DIR = obtener_ruta_certificados()
CERT_FILE = CERT_DIR / "tls-hgr.crt"
KEY_FILE = CERT_DIR / "tls-hgr.key"

# ======================================================
# Función para generar certificado TLS si no existe
# ======================================================
def generar_certificado_tls():
    try:
        CERT_DIR.mkdir(parents=True, exist_ok=True)

        if not (CERT_FILE.exists() and KEY_FILE.exists()):
            subprocess.run([
                "openssl", "req", "-new", "-newkey", "rsa:4096",
                "-days", "36500", "-nodes", "-x509",
                "-subj", "/C=SE/ST=NONE/L=NONE/O=GNOME/CN=gnome.org",
                "-out", str(CERT_FILE),
                "-keyout", str(KEY_FILE)
            ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

            # Dar permisos correctos al usuario dueño
            os.chmod(CERT_FILE, 0o600)
            os.chmod(KEY_FILE, 0o600)
        else:
            pass
    except PermissionError:
        print(f"❌ Permiso denegado al crear certificados en {CERT_DIR}")
        print("👉 Ejecuta esto para corregirlo:")
        print(f"   sudo mkdir -p {CERT_DIR} && sudo chown -R {getpass.getuser()}:{getpass.getuser()} {CERT_DIR}")
        exit(1)
    except Exception as e:
        print(f"Error al generar el certificado TLS: {e}")
        exit(1)

# ======================================================
# Función para comprobar conexión a Internet
# ======================================================
def hay_conexion(url="http://example.com", timeout=3):
    try:
        urllib.request.urlopen(url, timeout=timeout)
        return True
    except:
        return False

# ======================================================
# Clase de ventana de espera visual
# ======================================================
class VentanaEspera(Gtk.Window):
    def __init__(self):
        super().__init__(title="Sin conexión a Internet")

        self.set_default_size(400, 250)
        self.set_resizable(False)
        self.set_border_width(20)
        self.set_position(Gtk.WindowPosition.CENTER)

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=15)
        box.set_homogeneous(False)
        self.add(box)

        # Imagen
        if os.path.exists(ICONO_CONEXION):
            pixbuf = GdkPixbuf.Pixbuf.new_from_file(ICONO_CONEXION)
            pixbuf = pixbuf.scale_simple(64, 64, GdkPixbuf.InterpType.BILINEAR)
            imagen = Gtk.Image.new_from_pixbuf(pixbuf)
            box.pack_start(imagen, False, False, 0)

        # Texto
        label = Gtk.Label()
        label.set_markup(
            "<b>No se detecta conexión a Internet</b>\n"
            "Por favor, conecte el equipo a la red.\n\n"
            "La aplicación se iniciará automáticamente."
        )
        label.set_justify(Gtk.Justification.CENTER)
        label.set_line_wrap(True)
        box.pack_start(label, False, False, 0)

        # Botón cancelar
        boton_cancelar = Gtk.Button(label="Cancelar")
        boton_cancelar.connect("clicked", self.cerrar_aplicacion)
        box.pack_end(boton_cancelar, False, False, 0)

        # Comprobar conexión cada 3 segundos
        GLib.timeout_add_seconds(3, self.comprobar_conexion)

    def comprobar_conexion(self):
        if hay_conexion():
            self.close()
            iniciar_aplicacion()
            return False
        return True

    def cerrar_aplicacion(self, button):
        Gtk.main_quit()
        exit(1)

# ======================================================
# Lógica de inicio de la app principal
# ======================================================
def iniciar_aplicacion():
    s = SRunningControl(PID_FILE_SERVER)

    os.popen('sudo ' + str(SCRIPT_ETHERPAD_PROPIETARIO))
    os.spawnlp(os.P_NOWAIT, 'bash', 'bash', SCRIPT_ETHERPAD)

    if not s.is_running():
        s.create()
        hga = AppCore(GUI_SERVIDOR)
        hga.iniciar()
        s.remove()
    else:
        print("Ya hay una instancia de HGR en ejecución")

# ======================================================
# Flujo principal
# ======================================================
# 🔧 Crear carpeta y certificados dinámicamente por usuario
generar_certificado_tls()

if hay_conexion():
    iniciar_aplicacion()
else:
    win = VentanaEspera()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()

