/*
 * 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/event.h>
#include <drv/tty.h>
#include <drv/tty/types.h>
#include <drv/tty/ops.h>
#include <errno.h>
#include <stddef.h>

int drv_tty_write(struct drv_port *const p, const void *const buf,
    const size_t n, const struct drv_event_done *const d)
{
    for (const char *s = buf; s - (const char *)buf < n; s++)
    {
        struct row *const r = p->last_row;
        char *const col = &r->columns[p->last_column];

        if (*s == '\r')
        {
            *col = '\0';
            p->last_column = r->len = 0;
        }
        else
        {
            if (*s != '\n')
            {
                *col = *s;
                r->len++;
            }
            else
                *col = '\0';

            if (*s == '\n' || ++p->last_column >= p->ncolumns)
            {
                if (++p->last_row - p->rows >= p->nrows)
                    p->last_row = p->rows;

                if (p->last_row == p->first_row)
                {
                    if (++p->first_row - p->rows >= p->nrows)
                        p->first_row = p->rows;

                    p->proc_row = p->first_row;
                }

                p->last_column = 0;
            }
        }
    }

    return d->f(SUCCESS, d->args);
}
