/*
 * 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>
#include <string.h>

static int load(void *const buf, const size_t n, void *const args)
{
    size_t *const off = args;

    memcpy(buf, ttyfont + *off, n);
    *off += n;
    return 0;
}

struct drv_port *drv_tty_init(const struct drv_event *const ev)
{
    size_t off = 0;
    struct drv_port *ret = NULL;

    if (!(ret = malloc(sizeof *ret)))
        goto failure;

    *ret = (const struct drv_port){.ev = *ev};
    gfx_sprite_load(&ttyfont_spr, load, &off);

    if (drv_tty_setdim(ret, screen_w, screen_h))
        goto failure;

    return ret;

failure:
    drv_tty_free(ret);
    return NULL;
}
