/*
 * 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.h>
#include <drv/ps1/sio/ops.h>
#include <drv/ps1/sio/regs.h>
#include <drv/ps1/sio/routines.h>
#include <drv/ps1/sio/types.h>
#include <drv/event.h>
#include <kprintf.h>
#include <stddef.h>
#include <stdbool.h>

static int init(struct drv_ps1_sio *const s)
{
    if (s->init)
        return 0;

    const struct drv_event *const ev = &s->ev;
    static const struct drv_event_ops ops =
    {
        .read = drv_ps1_sio_read,
        .read_nb = drv_ps1_sio_read_nb,
        .write = drv_ps1_sio_write
    };

    if (ev->status("ttyS0", &ops, true, 0660, ev->args))
        return -1;

    s->init = true;
    return 0;
}

static int rx(struct drv_ps1_sio *const s)
{
    struct sio_fifo *const f = &s->rx;

    if (f->next)
        return f->next();
    else if (f->head)
        f->next = f->head->f;

    return 0;
}

static void write_tx(struct sio_fifo *const f)
{
    if (f->proc == f->pend)
        return;

    size_t n = f->proc + 1;

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

    SIO_TX_DATA->value = f->buf[f->proc = n];
}

static int tx(struct drv_ps1_sio *const s)
{
    struct sio_fifo *const f = &s->tx;

    if (SIO_STAT->bits.tx_ready_started)
        write_tx(f);

    if (f->next)
        return f->next();
    else if (f->head)
        f->next = f->head->f;

    return 0;
}

int sio_stat_overrun;

int drv_ps1_sio_update(struct drv_ps1_sio *const s)
{
    if (SIO_STAT->bits.rx_fifo_overrun)
    {
        sio_stat_overrun = 1;
        SIO_CTRL->bits.ack = 1;
    }

    if (init(s) || rx(s) || tx(s))
        return -1;

    return 0;
}
