// Copyright (C) 2026 Actia Nordic AB. All rights reserved.

#include <actia/actia.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>

#include "ipc.h"
#include "led_example.h"

#define IPC_ID (A_IPC_GUEST_MIN_ID + 9)

static event_loop_state_t event_loop_state = EVENT_LOOP_RUN;

void set_event_loop_state(event_loop_state_t state)
{
    event_loop_state = state;
}

static int event_loop(void)
{
    int rc = EXIT_SUCCESS;
    int epfd = epoll_create1(0);

    if (epfd < 0) {
        rc = EXIT_FAILURE;
        goto err_return;
    }

    int ipc_fd = ipc_initialize_actia_ipc(IPC_ID, epfd);

    if (ipc_fd < 0) {
        rc = EXIT_FAILURE;
        goto err_close_epfd;
    }

    A_IPC_RESULT ipc_rc = ipc_send_open_session_req(A_SERVICE_ID_SYSTEM);

    if (ipc_rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to send open session request: %s\n", a_ipc_result_str(ipc_rc));
        rc = EXIT_FAILURE;
        goto err_close_actia_ipc;
    }

    while (event_loop_state == EVENT_LOOP_RUN) {
        struct epoll_event events[3];
        int event_count = 0;

        do {
            event_count = epoll_wait(epfd, events, a_membersof(events), -1);
        } while (event_count < 0 && errno == EINTR);

        if (event_count > 0) {
            for (int e = 0; e < event_count; ++e) {
                if (ipc_handle_actia_ipc_event(&events[e])) {
                    /* Intentionally empty */
                } else {
                    fprintf(stderr, "Unexpected epoll_wait result\n");
                    set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
                }

                if (event_loop_state != EVENT_LOOP_RUN) {
                    break;
                }
            }
        } else if (event_count < 0) {
            fprintf(stderr, "Error while waiting for event: %d\n", errno);
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        }
    }

    if (event_loop_state != EVENT_LOOP_EXIT_OK) {
        rc = EXIT_FAILURE;
    }

err_close_actia_ipc:
    ipc_destroy_actia_ipc();
err_close_epfd:
    close(epfd);
err_return:
    return rc;
}

int main(void)
{
    printf("LEDs are fun\n");

    return event_loop();
}
