/*
 * 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/font.h>
#include <drv/tty/ops.h>
#include <drv/tty/types.h>
#include <gfx/gfx.h>
#include <gfx/sprite.h>
#include <stddef.h>
#include <stdlib.h>

int drv_tty_setdim(struct drv_port *const p, const unsigned w, const unsigned h)
{
    const unsigned columns = w / 10, rows = h / 16;
    struct row *const prs = malloc(rows * sizeof *prs);

    if (!prs)
        goto failure;

    for (unsigned i = 0; i < rows; i++)
        *(prs + i) = (const struct row){0};

    for (unsigned i = 0; i < rows; i++)
    {
        struct row *const p = &prs[i];
        char *const c = malloc(columns);

        if (!c)
            goto failure;

        p->columns = c;
    }

    p->first_row = p->last_row = p->proc_row = p->rows = prs;
    p->nrows = rows;
    p->ncolumns = columns;
    return 0;

failure:
    for (unsigned i = 0; i < rows; i++)
        free(prs[i].columns);

    free(prs);
    return -1;
}
