/*
 * tngp/font.c
 *
 * Copyright (C) 2022 bzt
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * @brief Font manager
 *
 */

#include "tngp.h"

uint8_t **font_buf = NULL;
ssfn_t fonts[FNT_LAST + 1];

/**
 * Initialize font manager
 */
void font_init()
{
    int i;

    font_buf = (uint8_t**)main_alloc(world.numfont * sizeof(uint8_t*));
    memset(fonts, 0, sizeof(fonts));
    for(i = 0; i < world.numfont; i++) {
        font_buf[i] = (uint8_t*)main_alloc(world.font[i].size);
        world_seektng(world.font[i].tng, 0, world.font[i].offs);
        if(!world_readtng(world.font[i].tng, 0, font_buf[i], world.font[i].size)) {
            if(verbose > 1) printf("tngp: error reading font %02X\r\n", i);
        }
    }
    for(i = 0; i < FNT_LAST; i++) {
        if(world.fonts[i].fnt >= 0 && world.fonts[i].fnt < world.numfont && font_buf[world.fonts[i].fnt])
            ssfn_load(&fonts[i], font_buf[world.fonts[i].fnt]);
        /* add default font so that rendering will have a fallback for missing glyphs */
        ssfn_load(&fonts[i], ssfn_src);
        ssfn_select(&fonts[i], SSFN_FAMILY_ANY, NULL, world.fonts[i].style | (i == FNT_CRD_HDR ? SSFN_STYLE_UNDERLINE : 0),
            world.fonts[i].size);
    }
    /* add a default font only option as last */
    ssfn_load(&fonts[i], ssfn_src);
    ssfn_select(&fonts[i], SSFN_FAMILY_ANY, NULL, SSFN_STYLE_REGULAR, 16);
}

/**
 * Free resources
 */
void font_free()
{
    int i;

    for(i = 0; i <= FNT_LAST; i++)
        ssfn_free(&fonts[i]);
    if(font_buf) {
        for(i = 0; i < world.numfont; i++)
            if(font_buf[i]) free(font_buf[i]);
        free(font_buf); font_buf = NULL;
    }
}

/**
 * Return a font
 */
ssfn_t *font_get(int idx)
{
    return &fonts[idx < 0 || idx >= FNT_LAST ? FNT_LAST : idx];
}

/**
 * Load a cutsom font
 */
ssfn_t *font_custom(world_font_t *fnt)
{
    ssfn_t *font = (ssfn_t*)main_alloc(sizeof(ssfn_t));
    if(font_buf && fnt && fnt->fnt >= 0 && fnt->fnt < world.numfont && font_buf[fnt->fnt]) ssfn_load(font, font_buf[fnt->fnt]);
    ssfn_load(font, ssfn_src);
    ssfn_select(font, SSFN_FAMILY_ANY, NULL, fnt ? fnt->style : SSFN_STYLE_REGULAR, fnt ? fnt->size : 16);
    font->style &= ~SSFN_STYLE_A;
    return font;
}

