/*
 * This file is part of the ufo utility.
 * Copyright (C) 2018-2020, 2025-2026 Eugene 'Vindex' Stulin
 * Distributed under the BSL 1.0 or the GNU GPL 3.0 or later.
 */

module de;

import std.algorithm : canFind;
import std.file : exists;
import std.process : environment;
import std.string : endsWith, toUpper, split;

import amalthea.sys : getAppPath;


enum DesktopEnvironment {
    Cinnamon,
    Enlightenment,
    GNOME,
    KDE,
    LXDE,
    LXQt,
    MATE,
    Pantheon,
    XFCE,
    None,
    Unknown
}
alias DE = DesktopEnvironment;


DE getCurrentDE() {
    DE de;
    string session;
    session = environment.get("XDG_CURRENT_DESKTOP", "");
    if (session == "") {  // XDG_CURRENT_DESKTOP doesn't exist in Bodhi Linux
        session = environment.get("XDG_SESSION_DESKTOP", "");
    }
    session = session.toUpper;
    switch(session) {
        case "X-CINNAMON":    de = DE.Cinnamon;      break;
        case "ENLIGHTENMENT": de = DE.Enlightenment; break;
        case "GNOME":         de = DE.GNOME;         break;
        case "KDE":           de = DE.KDE;           break;
        case "LXDE":          de = DE.LXDE;          break;
        case "LXQT":          de = DE.LXQt;          break;
        case "MATE":          de = DE.MATE;          break;
        case "PANTHEON":      de = DE.Pantheon;      break;
        case "XFCE":          de = DE.XFCE;          break;
        case "":              de = DE.None;          break;
        default:
            // for "GNOME-Classic:GNOME", "ubuntu:GNOME" or "Budgie:GNOME"
            de = session.endsWith(":GNOME") ? DE.GNOME : DE.Unknown;
            break;
    }
    return de;
}


/*******************************************************************************
 * Returns opening application depending on the desktop environment
 */
string chooseOpenerByDefault() {
    immutable gnomeTool    = "gio open";
    immutable kdeTool      = "kde-open";
    immutable standartTool = "xdg-open";
    immutable consoleTool  = "mimeopen";

    DE desktopSession = getCurrentDE();
    string opener;

    auto gnomeToolGroup = [
        DE.Cinnamon, DE.GNOME, DE.MATE, DE.Pantheon, DE.Enlightenment, DE.LXQt
    ];
    if (gnomeToolGroup.canFind(desktopSession)) {
        opener = gnomeTool;
    } else if (desktopSession == DE.KDE) {
        opener = kdeTool;
    } else if (desktopSession == DE.None) {
        opener = consoleTool;
    } else {
        if (getAppPath(gnomeTool) != "") {
            opener = gnomeTool;
        } else if (getAppPath(kdeTool) != "") {
            opener = kdeTool;
        }
    }

    if (getAppPath(opener) == "") {
        opener = standartTool;
        if (getAppPath(opener) == "") {
            opener = consoleTool;
            if (getAppPath(opener) == "") {
                opener = "";
            }
        }
    }

    return opener;
}
