/*Copyright (C) 2010-2012 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu 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.

Hikou no mizu 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 Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Font.hpp"

Font::Font(const FT_Library library, const std::string &path, int charSize) : m_charSize(charSize)
{
    FT_New_Face(library, path.c_str(), 0, &m_face);
    FT_Set_Char_Size(m_face, charSize << 6, charSize << 6, 72, 72);
}

Font::~Font()
{
    std::map<char, Glyph*>::iterator it;
    for (it = m_glyphsList.begin(); it != m_glyphsList.end(); it++)
        delete it->second;
        
    FT_Done_Face(m_face);
}

const Glyph *Font::getGlyph(char character)
{
    if (!isGlyphLoaded(character))
        loadGlyph(character);
    
    return m_glyphsList[character];
}

int Font::getCharSize() const
{
    return m_charSize;
}

void Font::loadGlyph(char character)
{
    FT_UInt glyphIndex = FT_Get_Char_Index(m_face, character);
    
    FT_Load_Glyph(m_face, glyphIndex, FT_LOAD_DEFAULT);
    FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_NORMAL);
    
    Glyph *glyph = new Glyph();
    glyph->load(m_face->glyph);
    
    m_glyphsList[character] = glyph;
}

bool Font::isGlyphLoaded(char character)
{
    std::map<char, Glyph*>::iterator it;
    it = m_glyphsList.find(character);
    
    if (it != m_glyphsList.end())
        return true;
    
    return false;
}
