pragma Singleton

import QtQuick
import Quickshell
import Quickshell.Io

Singleton {
    id: data
    property var tags: {}
    property var keys: []
    Timer {
        id: reconnectTimer
        running: false
        repeat: true
        onTriggered: () => sock.connected = true
        interval: 5000
    }

    Socket {
        id: sock
        connected: true
        onConnectionStateChanged: () => {
            reconnectTimer.running = sock.connected ? false : true
            if (!sock.connected) {
                data.tags = {}
                data.keys = []
            }
        }
        path: Quickshell.env("XDG_RUNTIME_DIR") + "/niri-tag-events.sock"
        parser: SplitParser {
            onRead: tag_data => {
                let event = JSON.parse(tag_data);

                let ensure = (d, t) => {
                    if (!d[t]) {
                        d[t] = {
                            occupied: false,
                            urgent: false,
                            enabled: false,
                            id: t
                        };
                    }
                    return d;
                };

                if (event.TagEmpty) {
                    data.tags = ensure(data.tags, event.TagEmpty);
                    data.tags[event.TagEmpty].occupied = false;
                } else if (event.TagOccupied) {
                    data.tags = ensure(data.tags, event.TagOccupied);
                    data.tags[event.TagOccupied].occupied = true;
                } else if (event.TagUrgent) {
                    data.tags = ensure(data.tags, event.TagUrgent);
                    data.tags[event.TagUrgent].urgent = true;
                } else if (event.TagEnabled) {
                    data.tags = ensure(data.tags, event.TagEnabled);
                    data.tags[event.TagEnabled].enabled = true;
                } else if (event.TagDisabled) {
                    data.tags = ensure(data.tags, event.TagDisabled);
                    data.tags[event.TagDisabled].enabled = false;
                } else if (event.TagExclusive) {
                    data.tags = ensure(data.tags, event.TagExclusive);
                    for (const [k] of Object.keys(data.tags)) {
                        data.tags[k].enabled = false;
                    }
                    data.tags[event.TagExclusive].enabled = true;
                } else if (event.TagFullState) {
                    data["tags"] = event.TagFullState;
                    for (const [k, v] of Object.entries(data.tags)) {
                        data.tags[k].id = k;
                    }
                }

                data.keys = Object.keys(data.tags);
                data.tagsChanged();
                data.keysChanged();
            }
        }
    }
}
