/*
 * 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 <drv/ps1/sio/ops.h>
#include <drv/ps1/sio/routines.h>
#include <drv/ps1/sio/types.h>
#include <drv/ps1/bios.h>
#include <drv/event.h>
#include <kprintf.h>
#include <sys/types.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>

static int store(void);

static void write_fifo(struct drv_ps1_sio *const s)
{
    struct sio_fifo *const f = &s->tx;
    struct sio_req *const r = f->head;
    struct sio_req_w *const w = &r->u.w;
    const char *p = w->buf;

    while (w->n)
    {
        size_t n = f->pend + 1;

        if (n >= sizeof f->buf)
            n = 0;
        else if (n == f->proc)
            break;

        f->buf[f->pend = n] = *p++;
        w->buf = p;
        w->n--;
    }
}

static int check(void)
{
    struct drv_ps1_sio *const s = &drv_ps1_sio;
    struct sio_fifo *const f = &s->tx;
    struct sio_req *const r = f->head;
    struct sio_req_w *const w = &r->u.w;

    if (!w->n)
    {
        const struct drv_event_done *const d = &r->done;

        if (d->f && d->f(SUCCESS, d->args))
            return -1;

        return drv_ps1_sio_next(f);
    }

    f->next = store;
    return 0;
}

static int store(void)
{
    struct drv_ps1_sio *const s = &drv_ps1_sio;
    struct sio_fifo *const f = &s->tx;
    struct sio_req_w *const w = &f->head->u.w;

    write_fifo(s);

    if (!w->n)
        f->next = check;

    return 0;
}

int drv_ps1_sio_write(struct drv_port *const p, const void *const buf,
    const size_t n, const struct drv_event_done *const done)
{
    struct drv_ps1_sio *const s = &drv_ps1_sio;
    struct sio_fifo *const f = &s->tx;
    struct sio_req *const req = malloc(sizeof *req);

    if (!req)
        return -1;

    *req = (const struct sio_req)
    {
        .f = store,
        .done = *done,
        .u.w =
        {
            .buf = buf,
            .n = n
        }
    };

    if (!f->head)
        f->head = req;
    else
        f->tail->next = req;

    f->tail = req;
    return 0;
}
