#include <stdio.h>
#include <systemd/sd-bus.h>

// 1. Handle Method Calls (Play, Pause, etc.)
static int handle_play_pause(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
    printf("Action: Play/Pause toggled!\n");
    return sd_bus_reply_method_return(m, NULL);
}

// 2. Define the MPRIS Interface VTable
static const sd_bus_vtable mpris_vtable[] = {
    SD_BUS_VTABLE_START(0),
    // Methods
    SD_BUS_METHOD("PlayPause", NULL, NULL, handle_play_pause, SD_BUS_VTABLE_UNPRIVILEGED),
    // Properties (Metadata is complex, Status is a simple string)
    SD_BUS_PROPERTY("PlaybackStatus", "s", NULL, offsetof(struct my_player, status), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
    SD_BUS_VTABLE_END
};

int main() {
    sd_bus *bus = NULL;
    int r;

    // Connect to the user session bus
    r = sd_bus_open_user(&bus);
    if (r < 0) return fprintf(stderr, "Failed to connect to bus: %s\n", strerror(-r));

    // Own the MPRIS name so menus find you
    r = sd_bus_request_name(bus, "org.mpris.MediaPlayer2.MyCPlayer", 0);
    if (r < 0) return fprintf(stderr, "Failed to acquire name: %s\n", strerror(-r));

    // Register the object path and interfaces
    r = sd_bus_add_object_vtable(bus, NULL,
                                 "/org/mpris/MediaPlayer2",
                                 "org.mpris.MediaPlayer2.Player",
                                 mpris_vtable,
                                 NULL);

    printf("Player active. Press Ctrl+C to stop.\n");

    for (;;) {
        r = sd_bus_process(bus, NULL);
        if (r < 0) break;
        if (r > 0) continue;
        r = sd_bus_wait(bus, (uint64_t) -1);
        if (r < 0) break;
    }

    sd_bus_unref(bus);
    return 0;
}
