//This code is copyright Andrew Story (Kaslai/Aslai) All rights reserved.
//This and derivative works can be distributed as seen fit,
//so long as this notice remains unchanged and present

#include "engine/font.h"
#include "engine/types.h"

std::vector<Font*> fonts;
std::map<const char*, int, map_char> font_map;

void Font::draw( int x, int y, const char* tex )
{
    unsigned char* text = (unsigned char*) tex;
    int dx = x, dy = y;
    for( int i = 0; text[i] != 0; i ++ ){
        if( text[i] >= 0x20 ){
            //printf("X = %i\t", ((int)(lookup[text[i]])) * (w) );
            parent->draw_image_part( dx, dy, ((int)(lookup[text[i]])) * (w), 0, w, h, img );
        }
        else switch( text[i] ){
            case '\n':
                dx = x - w - hs;
                dy += h + vs;
                break;
            case '\t':
                dx = ( ( ( dx - x ) / ( hs + w ) + 1 ) / 4 ) * (4 * (w + hs) ) + x - hs - w;
                break;
        }
        dx += hs + w;
    }
}

void Font::drawf( int x, int y, const char* tex, ... )
{
    va_list a;
    va_start( a, tex );
    int blen = vsnprintf( 0, 0, tex, a ) + 1;
    char* buf = (char*) malloc( blen );
    va_end( a );

    va_start( a, tex );
    vsnprintf( buf, blen, tex, a );
    va_end( a );
    draw( x, y, buf );
    free( buf );
}

Font::Font( CImage image, Context* prnt, int framecnt, int wid, int hig, int hspace, int vspace, char* ID, const unsigned char* idstr )
{
    frames = framecnt;
    img = image;
    w = wid;
    h = hig;
    hs = hspace;
    vs = vspace;
    parent = prnt;
    id = (char*) malloc( strlen( ID ) + 1 );
    strcpy( id, ID );
    memset( lookup, 0, 256 );
    for( int i = 0; idstr[i] != 0; i ++ )
        lookup[idstr[i]] = i;
    //for( int i = 0; i < 256; i ++ ){
        //printf( "%i\t", lookup[i] );
    //}
}
Font::~Font(){
    free( id );
}

Font* font_add( CImage img, Context* cnt, int framecnt, int wid, int hig, int hspace, int vspace, char* ID, const unsigned char* idstr )
{
    Font* a = new Font( img, cnt, framecnt, wid, hig, hspace, vspace, ID, idstr );
    int pos = fonts.size();
    fonts.push_back( a );
    font_map[a->id] = pos;
    a->pos = pos;
    return a;
}

void font_rem( Font* fnt )
{
    delete fonts[fnt->pos];
    fonts[fnt->pos] = 0;
    //delete fnt;
}

Font* font_get_by_id( char* ID )
{
    return fonts[font_map[ID]];
}