/*
 * 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/ps1/bios.h>
#include <drv/ps1/cpu.h>
#include <drv/ps1/irq.h>
#include <drv/event.h>

struct drv_ps1_sio *drv_ps1_sio_init(const struct drv_event *const ev)
{
    const unsigned long baudrate = 115200ul;

    SIO_CTRL->bits.reset = 1;
    SIO_BAUD = DRV_PS1_CPU_F / (16 * baudrate);
    SIO_MODE->mask = (const union sio_mode)
    {
        .bits =
        {
            .baudrate_mul = SIO_MODE_FACTOR_MUL16,
            .stplen = SIO_MODE_STP_1,
            .len = SIO_MODE_LEN_8
        }
    }.mask;

    SIO_CTRL->mask = (const union sio_ctrl)
    {
        .bits =
        {
            .rx_int_mode = SIO_CTRL_RX_INT_1,
            .rx_int_en = 1,
            .tx_en = 1,
            .rx_en = 1,
            .rts = 1,
            .dtr = 1
        }
    }.mask;

    static struct drv_ps1_irq_src src =
    {
        .mask = 1 << IRQ_SIO,
        .fn = drv_ps1_sio_irq
    };

    if (drv_ps1_irq_set(&src))
        return NULL;

    I_MASK->bits.sio = 1;
    drv_ps1_sio.ev = *ev;
    return &drv_ps1_sio;
}
