pragma Singleton

import QtQuick
import Quickshell
import Quickshell.Io

Singleton {
    id: data
    property var currentWindow: " "
    property var currentId: 0
    property var windows: {}
    Process {
        id: proc
        command: ["niri", "msg", "-j", "event-stream"]
        running: true
        stdout: SplitParser {
            onRead: niri_data => {
                var event = JSON.parse(niri_data);
                if (event.WindowsChanged) {
                    let new_data = event.WindowsChanged.windows.reduce((acc, el) => {
                        acc[el.id] = el.title == "" ? el.app_id : el.title;
                        return acc;
                    }, {});
                    data.windows = new_data;
                    let focused = event.WindowsChanged.windows.find(w => w.is_focused);
                    if (focused === undefined) {
                        data.currentId = 0;
                    }
                } else if (event.WindowOpenedOrChanged) {
                    let target = event.WindowOpenedOrChanged.window;
                    data.windows[target.id] = target.title == "" ? target.app_id : target.title;
                    if (target.is_focused) {
                        data.currentId = target.id;
                    }
                } else if (event.WindowClosed) {
                    delete data[event.WindowClosed.id];
                    if (Object.keys(data).length == 0) {
                        data.currentId = 0;
                    }
                } else if (event.WindowFocusChanged) {
                    if (event.WindowFocusChanged.id === null) {
                        data.currentId = 0;
                    } else {
                        data.currentId = event.WindowFocusChanged.id;
                    }
                }

                data.currentWindow = data.currentId == 0 ? "                   " : data.windows[data.currentId];
            }
        }
    }
}
