/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <aio.h>
#include <aio/types.h>
#include <state.h>
#include <stdbool.h>
#include <stddef.h>
#include <time.h>

int aio_poll(struct aio_poll *const poll, int ms)
{
    struct timespec init;

    if (ms > 0 && clock_gettime(CLOCK_REALTIME, &init))
        return -1;

    do
    {
        for (struct aio_poll *p = poll; p;)
        {
            struct aio_poll *const next = p->next;
            const struct aio *const aio = p->aio;
            const struct fs_ret *const r = &aio->r;
            const enum state s = r->f(r->args);

            switch (s)
            {
                case STATE_AGAIN:
                    break;

                case STATE_FATAL:
                    p->error = aio->error;
                    /* Fall through */
                case STATE_OK:
                {
                    const struct aio_done *const d = &aio->done;

                    if (d->f)
                        return d->f(s, d->args) ? -1 : 1;

                    p->done = true;
                    return 1;
                }
            }

            p = next;
        }

        if (ms > 0)
        {
            struct timespec after;

            if (clock_gettime(CLOCK_REALTIME, &after))
                return -1;

            /* TODO */
        }
    } while (ms);

    return 0;
}
