import Apps from "gi://AstalApps"
import AstalHyprland from "gi://AstalHyprland";

const app_icons = new Apps.Apps().list.reduce(
    (acc, app) => {
        if (app.icon_name) {
            acc.classOrNames[app.wm_class ?? app.name] = app.icon_name;
            acc.executables[app.executable] = app.icon_name;
        }
        return acc;
    },
    { classOrNames: {}, executables: {} },
);

export function getIconName(client: AstalHyprland.Client) {
    if (!client) {
        return "";
    }

    let icon = app_icons.classOrNames[client.class];
    if (!icon) {
        const icon_key = Object.keys(app_icons.classOrNames).find(
            (key) =>
                key.includes(client.title) ||
                key.includes(client.initialTitle) ||
                key.includes(client.initialClass) ||
                key.includes(client.class),
        );
        if (icon_key) {
            icon = app_icons.classOrNames[icon_key];
            app_icons.classOrNames[client.class] = icon;
        }
    }

    if (!icon) {
        app_icons.classOrNames[client.class] = "";
    }

    return icon;
}
