// Adds an installed application to the user's freedesktop autostart directory.

import QtQuick
import Quickshell
import qs.config
import qs.modules.clipboard

Column {
    id: root

    required property var existing
    signal picked(string id)

    spacing: 0

    function desktopId(entry: var): string {
        const id = String(entry?.id ?? "");
        return id.endsWith(".desktop") ? id : id + ".desktop";
    }

    readonly property var matches: {
        const needle = search.text.trim().toLowerCase();
        if (needle === "")
            return [];
        const out = [];
        for (const entry of DesktopEntries.applications.values) {
            const desktopId = root.desktopId(entry);
            if (entry.noDisplay || root.existing.indexOf(desktopId) >= 0)
                continue;
            const haystack = `${entry.name ?? ""} ${entry.genericName ?? ""} ${desktopId}`.toLowerCase();
            if (haystack.indexOf(needle) >= 0)
                out.push(entry);
            if (out.length >= 8)
                break;
        }
        return out;
    }

    SearchField {
        id: search
        width: parent.width
        placeholder: "Search installed applications"
    }

    Repeater {
        model: root.matches

        SettingRow {
            id: candidate

            required property var modelData
            required property int index

            label: String(candidate.modelData.name || root.desktopId(candidate.modelData))
            detail: String(candidate.modelData.genericName || root.desktopId(candidate.modelData))
            divider: candidate.index < root.matches.length - 1
            controlWidth: 86

            SettingsButton {
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                text: "Add"
                onClicked: {
                    root.picked(root.desktopId(candidate.modelData));
                    search.text = "";
                }
            }
        }
    }

    SettingRow {
        visible: search.text.trim() !== "" && root.matches.length === 0
        label: "No matching applications"
        detail: "Only installed desktop applications can start with the session"
        divider: false
    }
}
