/*
 * UPIWIN - Micro Pi Windowing Framework Kernel
 * Copyright (C) 2019 Amy Bowersox/Erbosoft Metaverse Design Solutions
 *    
 * 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 2 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *-------------------------------------------------------------------------
 */
#include <ft2build.h>
#include FT_FREETYPE_H
#include "scode.h"
#include "config.h"
#include "log.h"
#include "fontengine.h"

static FT_Library library;
static FT_Face stdfont;

static void fonteng_cleanup(void)
{
  FT_Done_Face(stdfont);
  FT_Done_FreeType(library);
}

HRESULT FontEng_setup(void)
{
  HRESULT hr = S_OK;
  FT_Error err;
  
  err = FT_Init_FreeType(&library);
  if (err != 0)
  {
    Log(LFATAL, "Unable to initialize Freetype (%d)", err);
    return E_FAIL;
  }

  err = FT_New_Face(library, "/usr/local/share/fonts/truetype/arial.ttf", 0, &stdfont);
  if (err != 0)
  {
    Log(LFATAL, "Unable to load font (%d)", err);
    hr = E_FAIL;
    goto error_0;
  }

  err = FT_Set_Pixel_Sizes(stdfont, 0, 16);
  if (err != 0)
  {
    Log(LFATAL, "Unable to set font size (%d)", err);
    hr = E_FAIL;
    goto error_1;
  }

  hr = Config_exitfunc(fonteng_cleanup);
  if (FAILED(hr))
    fonteng_cleanup();
  return hr;

error_1:
  FT_Done_Face(stdfont);
error_0:
  FT_Done_FreeType(library);
  return hr;
}

HRESULT FontEng_do_text_out(INT32 x, INT32 y, PCSTR pstr, TEXTOUTFUNC renderfunc)
{
  HRESULT hr = S_OK;
  FT_GlyphSlot slot = stdfont->glyph;
  FT_UInt glyph_index;
  FT_Error err;

  y += (stdfont->size->metrics.ascender >> 6);

  while (*pstr)
  {
    glyph_index = FT_Get_Char_Index(stdfont, *pstr);
    err = FT_Load_Glyph(stdfont, glyph_index, FT_LOAD_DEFAULT);
    if (err != 0)
    {
      hr = E_FAIL;
      break;
    }
    err = FT_Render_Glyph(stdfont->glyph, FT_RENDER_MODE_NORMAL);
    if (err != 0)
    {
      hr = E_FAIL;
      break;
    }
    (*renderfunc)(x + slot->bitmap_left, y - slot->bitmap_top, slot->bitmap.width,
		  slot->bitmap.rows, slot->bitmap.buffer);
    x += slot->advance.x >> 6;
    y += slot->advance.y >> 6;
    pstr++;
  }
  return hr;
}
