/*
 * fonts.c
 *
 *  Created on: 23 maj 2021
 *      Author: bartool
 */

// #include "main.h"
#include "font_gfx.h"

static uint8_t font_string_lenght_px(const GFX_font_t *font, uint8_t *text);

/**
 * @brief Write string at at the specified (x,y) position.
 * @param disp A pointer to display struct
 * @param font A pointer to font struct.
 * @param text A pointer to string data.
 * @param pos_x Top left corner x coordinate
 * @param pos_yTop left corner y coordinate
 * @param color Color of pixel BM_NORMAL or BM_INVERSE for bitmap.
 * @return uint8_t
 */
uint8_t DISP_writeString(GFX_display_t *disp, const GFX_font_t *font, uint8_t *text, uint8_t pos_x, uint8_t pos_y, GFX_BitmapColor_t color)
{
	uint8_t actual_char, char_nr;
	GFX_bitmap_t char_bitmap;
	const GFX_fontChar_t *charinfo;

	uint8_t height = font->heightPixels;
	uint8_t x = pos_x;
	uint8_t width = font_string_lenght_px(font, text);

	switch (color)
	{
	case BM_INVERSE:;
		DISP_drawFillRect(disp, pos_x - 1, pos_y - 1, width + 2, height + 2);
		break;
	default:
		DISP_clearRegion(disp, pos_x - 1, pos_y - 1, width + 2, height + 2);
		break;
	}

	while (*text)
	{
		actual_char = *text++;
		if (actual_char < font->startChar || actual_char > font->endChar)
		{
			if (actual_char == ' ')
			{
				x += font->spacePixels;
			}
			continue;
		}

		char_nr = actual_char - font->startChar;
		charinfo = &font->charInfo[char_nr];

		char_bitmap.height = height,
		char_bitmap.width = charinfo->widthBits,
		char_bitmap.bitmap = font->data + charinfo->offset,

		DISP_drawBitmap(disp, &char_bitmap, x, pos_y, color);

		x += charinfo->widthBits + font->interspacePixels;
	}

	return x;
}

static uint8_t font_string_lenght_px(const GFX_font_t *font, uint8_t *text)
{
	uint8_t width = 0;
	while (*text)
	{
		uint8_t actual_char = *text++;
		uint8_t char_nr = actual_char - font->startChar;
		if (actual_char < font->startChar || actual_char > font->endChar)
		{
			if (actual_char == ' ')
			{
				width += font->spacePixels;
			}
			continue;
		}
		width += font->charInfo[char_nr].widthBits + font->interspacePixels;
	}
	return width;
}
