import AstalTray from 'gi://AstalTray';
import {
    GObject
} from 'astal';
import {
    Gtk
} from 'astal/gtk4';

const SYNC = GObject.BindingFlags.SYNC_CREATE;

const SysTray = () => {
    const trayBox = new Gtk.Box( {
        'cssClasses': [ '' ]
    } );
    const tray = AstalTray.get_default();
    const trayItems = new Map<string, Gtk.MenuButton>();
    const trayAddedHandler = tray.connect( 'item-added', ( _, id ) => {
        const item = tray.get_item( id );
        const popover = Gtk.PopoverMenu.new_from_model( item.menu_model );
        const icon = new Gtk.Image();
        const button = new Gtk.MenuButton( {
            popover,
            'child': icon,
            'cssClasses': [ 'tray-item' ],
        } );

        item.bind_property(
            'gicon', icon, 'gicon', SYNC
        );
        popover.insert_action_group( 'dbusmenu', item.action_group );
        item.connect( 'notify::action-group', () => {
            popover.insert_action_group( 'dbusmenu', item.action_group );
        } );

        trayItems.set( id, button );
        trayBox.append( button );
    } );
    const trayRemovedHandler = tray.connect( 'item-removed', ( _, id ) => {
        const button = trayItems.get( id );

        if ( button ) {
            trayBox.remove( button );
            button.run_dispose();
            trayItems.delete( id );
        }
    } );

    trayBox.connect( 'destroy', () => {
        tray.disconnect( trayAddedHandler );
        tray.disconnect( trayRemovedHandler );
    } );

    return trayBox;
};

const TrayPopover = () => {
    const popover = new Gtk.Popover( {
        'cssClasses': [ 'TrayPopover' ]
    } );

    popover.set_child( SysTray() );

    return popover;
};

const SystemTray = () => {
    const systray = TrayPopover();

    return (
        <button
            widthRequest={0}
            hexpand={false}
            vexpand={false}
            cssClasses={[ 'power-menu-button' ]}
            child={
                <box>
                    <image iconName={'systemtray'}></image>
                    {systray}
                </box>
            }
            onClicked={() => systray.popup()}
        />
    );
};

export default {
    SystemTray
};
