/* extension.js
 * Extension GNOME Shell - Dashboard Launcher
 * Ajoute une icône dans la barre supérieure pour lancer/fermer le Dashboard
 * Toggle: clic = affiche, re-clic = ferme
 *
 * Compatible GNOME 45+ (ESM)
 */

'use strict';

import GObject from 'gi://GObject';
import St from 'gi://St';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';

import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';

const APP_PATH = GLib.build_filenamev(['/home/gilles/Documents/vscode/ssh-web-launcher', 'app', 'ssh-launcher-gtk.py']);
const PID_FILE = '/tmp/dashboard-launcher.pid';

const DashboardLauncherIndicator = GObject.registerClass(
class DashboardLauncherIndicator extends PanelMenu.Button {
    _init() {
        super._init(0.0, 'Dashboard Launcher');

        // Icône dans la barre (style dashboard/grille)
        this._icon = new St.Icon({
            icon_name: 'view-app-grid-symbolic',
            style_class: 'system-status-icon dashboard-launcher-icon',
        });

        this.add_child(this._icon);

        // Connexion du clic
        this.connect('button-press-event', this._onClick.bind(this));
    }

    _onClick() {
        this._toggleApp();
        return true;
    }

    _isRunning() {
        // Vérifie si le dashboard est en cours d'exécution
        try {
            let file = Gio.File.new_for_path(PID_FILE);
            if (file.query_exists(null)) {
                let [success, contents] = file.load_contents(null);
                if (success) {
                    let pid = parseInt(new TextDecoder().decode(contents).trim());
                    // Vérifier si le processus existe (signal 0)
                    try {
                        let checkProc = new Gio.Subprocess({
                            argv: ['kill', '-0', pid.toString()],
                            flags: Gio.SubprocessFlags.NONE,
                        });
                        checkProc.init(null);
                        checkProc.wait(null);
                        return checkProc.get_successful();
                    } catch (e) {
                        return false;
                    }
                }
            }
        } catch (e) {
            // Fichier n'existe pas ou erreur de lecture
        }
        return false;
    }

    _toggleApp() {
        try {
            if (this._isRunning()) {
                // Dashboard ouvert -> le fermer avec --toggle
                let subprocess = new Gio.Subprocess({
                    argv: ['python3', APP_PATH, '--toggle'],
                    flags: Gio.SubprocessFlags.NONE,
                });
                subprocess.init(null);
            } else {
                // Dashboard fermé -> l'ouvrir
                let subprocess = new Gio.Subprocess({
                    argv: ['python3', APP_PATH],
                    flags: Gio.SubprocessFlags.NONE,
                });
                subprocess.init(null);
            }
        } catch (e) {
            logError(e, 'Dashboard Launcher: Erreur lors du toggle');
        }
    }
});

export default class DashboardLauncherExtension {
    constructor() {
        this._indicator = null;
    }

    enable() {
        this._indicator = new DashboardLauncherIndicator();
        Main.panel.addToStatusArea('dashboard-launcher', this._indicator);
    }

    disable() {
        if (this._indicator) {
            this._indicator.destroy();
            this._indicator = null;
        }
    }
}
