#include "vfs.h"
#include <lib/font.h>
#include <lib/memory.h>

#include <stddef.h>

psf_font_t* load_font(const char* path) {
    int fd = vfs_open(path, 0);
    if (fd == -1) {
        return NULL;
    }

    psf_hdr_t* header = kalloc(sizeof(psf_hdr_t));
    int rd = vfs_read(fd, header, sizeof(psf_hdr_t));
    if (rd <= 0) {
        kfree(header);
        return NULL;
    }

    uint32_t num_glyphs = (header->mode & (1 << 0)) ? 512 : 256;
    uint32_t glyph_sz = header->charsz;
    uint32_t glyph_buf_sz = num_glyphs * glyph_sz;

    void* glyphs = kalloc(glyph_buf_sz);

    rd = 0;
    rd = vfs_read(fd, glyphs, glyph_buf_sz);
    if (rd <= 0) {
        kfree(header);
        kfree(glyphs);
        return NULL;
    }

    psf_font_t* font = kalloc(sizeof(psf_font_t));
    font->hdr = header;
    font->glyphs = glyphs;
    return font;
}

void free_font(psf_font_t* font) {
    kfree(font->glyphs);
    kfree(font->hdr);
    kfree(font);
}