/*---------------------------------------------------------------------------------
 libBAG  Copyright (C) 2010 - 2012		
  BassAceGold - <BassAceGold@gmail.com>

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any
  damages arising from the use of this software.

  Permission is granted to anyone to use this software for any
  purpose, including commercial applications, and to alter it and
  redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you
     must not claim that you wrote the original software. If you use
     this software in a product, an acknowledgment in the product
     documentation would be appreciated but is not required.
	 
  2. Altered source versions must be plainly marked as such, and
     must not be misrepresented as being the original software.
	 
  3. Restricting the usage of or portions of code in this library
     from other software developers and or content creators
     is strictly prohibited in applications with software creation capabilities
     and or with the intent to profit from said restrictions.
	 
  4. This notice may not be removed or altered from any source
     distribution.
---------------------------------------------------------------------------------*/

#include "BitTextSys.h"
#include "../text.h"
#include "../../Draw.h"

static u8 charToU8(char character){
    if(character < 0)
        return (127 + abs(character));

    return character;
}

static void getCharBitmap(BitFnt_t *font, char character, int *x, int *y){
    u8 newChar = charToU8(character);
    font->charactersPerRow = (*BAG_Display_GetGfxWidth(&font->graphic)) / font->tileWd;
    *y = abs((int)charToU8(newChar) / font->charactersPerRow);
    *x = abs((int)charToU8(newChar) - ((*y) * font->charactersPerRow));

    *x *= font->tileWd;
    *y *= font->tileHt;
}

static void calculateCharSize(BitFnt_t *font, char character, char *wd, char *ht){
    if(character == ' '){
        (*wd) = font->Spaces.space;
        (*ht) = 1;
        return;
    }   
    int drawX = font->tileWd-1,
        drawY = font->tileHt-1,
        dataX = 0,
        dataY = 0;

    getCharBitmap(font, character, &dataX, &dataY);
    unsigned short *buffer = BAG_Display_GetGfxBuf(&font->graphic);
    register int srcWidth = (*BAG_Display_GetGfxWidth(&font->graphic));

    u16 pixel = 0;
    while(drawY >= 0){
        drawX = font->tileWd-1;
        while(drawX >= 0){
            register int posX = dataX + drawX;
            register int posY = dataY + drawY;

            pixel = buffer[posX + (posY * srcWidth)];
            if(pixel != (*BAG_Display_GetGfxTranspCol(&font->graphic))){
                if(drawX >= (*wd))
                    (*wd) = drawX;
                if(drawY >= (*ht))
                    (*ht) = drawY;
            }   
            drawX--;
        }
        drawY--;
    }
}

static void collectSizes(BitFnt_t *font){
    register int i = 0;
    for(i = 0; i < 224; i++){
        calculateCharSize(font, (char)(i + 32), &font->character_width[i], &font->character_height[i]);
        font->character_width[i]++;
        font->character_height[i]++;
    }
}

static char getCharWidth(BitFnt_t *font, char character){
    int pos = charToU8(character) - 32;
    if(pos < 0)
        return 0;

    return font->character_width[pos]; 	
}

char BAG_BitText_getCharWidth(FNTObj_t *object, char character){
	BitFnt_t *font = object->bitmap_font;
	return getCharWidth(font, character);
}



static char getCharHeight(BitFnt_t *font, char character){
    int pos = charToU8(character) - 32;
    if(pos < 0)
        return 0;

    return font->character_height[pos]; 	
}

char BAG_BitText_getCharHeight(FNTObj_t *object, char character){
	BitFnt_t *font = object->bitmap_font;
	return getCharHeight(font, character);
}




void BAG_BitText_SetFontDrawSize(FNTObj_t *object, int size){
	BitFnt_t *font = object->bitmap_font;
	font->tileWd = font->tileHt = size;
}

int BAG_BitText_LoadFont(const char *filename, FNTObj_t *object){
	BitFnt_t *font = object->bitmap_font;
    int load = BAG_Display_LoadObj(filename, &font->graphic);
    if( load != ERR_NONE){
        BAG_DBG_LibMsg(OPEN_FAIL_MSG, filename);
        return load;
    }

    //store size of every text character
    collectSizes(font);
    font->Spaces.space = getCharWidth(font, 'A');
    font->Spaces.letter = 1;
    font->Spaces.newLine = getCharHeight(font, 'j') + 1;
    font->init++;
    return ERR_NONE;
}

void BAG_BitText_UnloadFont(FNTObj_t *object){
	BitFnt_t *font = object->bitmap_font;
    if(font == NULL || font->init == 0)
        return; 
    //unload font data
    BAG_Display_DeleteObj(&font->graphic);
    free(object->bitmap_font);
    object->bitmap_font = NULL;
}

static void BAG_BitText_DrawBitmap(u16 *Dest, int destWd, int destHt, BitFnt_t *font, char character, int x, int y, int x2, int y2, unsigned short color){
    int drawX = font->tileWd-1,
        drawY = font->tileHt-1,
        dataX = 0,
        dataY = 0;

    getCharBitmap(font, character, &dataX, &dataY);
    unsigned short *buffer = BAG_Display_GetGfxBuf(&font->graphic);
    register int srcWidth = (*BAG_Display_GetGfxWidth(&font->graphic));

    u16 pixel = 0;
    while(drawY >= 0){
        drawX = font->tileWd - 1;
        while(drawX >= 0){
            register int inposX = dataX + drawX;
            register int inposY = dataY + drawY;

            pixel = buffer[inposX + (inposY * srcWidth)];
            if(pixel != (*BAG_Display_GetGfxTranspCol(&font->graphic)) && drawX + x < x2 && drawY + y <y2 ){
                Dest[x + drawX + ((y+drawY) * destWd)] = color;
                //BAG_Draw_BlitPixel(Dest, destWd, destHt, drawX + x, drawY + y, color);
            }   
            drawX--;
        }
        drawY--;
    }
}


void BAG_BitText_SetCharMode(struct FNTChar_s *character, char rotMode){
	character->rot = rotMode;
	switch(rotMode){
		default:
			character->blitCharBit = (void*)&BAG_BitText_DrawBitmap;
		break;
		//case TEXTROT_RIGHT:
		//	character->blitChar = (void*)&BAG_Freetype_DrawFTBitmap_right;
		//break;	
	}
}

void BAG_BitText_DrawBitChar(u16 *dest, int destWd, int destHt, struct FNTChar_s *character){
	BitFnt_t *font = character->bitmap_font;

	if(character->character == '\n'){//newline, drop one line down
		int ascent = font->Spaces.newLine;
		switch(character->rot){
			default: character->drawy += ascent; break;
			case TEXTROT_RIGHT: character->drawx -= ascent; break;
		}
	}
	
	else if(character->character != ' '){//standard character
		if(character->blitCharBit != NULL)
			character->blitCharBit(dest, destWd, destHt, font, character->character, character->drawx, character->drawy, character->x2, character->y2, character->color);	
	}
	//advance a space if character is not a new line or if the space symbol is entered
	if(character->character != '\n'){
		int xinc = getCharWidth(font, character->character) + font->Spaces.letter;
		switch(character->rot)
		{
			default: 
                character->drawx += xinc; 
                character->newlinePos = character->drawy + getCharHeight(font, character->character);
            break;
			case TEXTROT_RIGHT: 
                character->drawy += xinc; 
                character->newlinePos = character->drawx + getCharWidth(font, character->character);
            break;
		}

	}
}



int BAG_BitText_FontInit(FNTObj_t *font){
	if(font->bitmap_font == NULL){
		font->bitmap_font = calloc( 1, sizeof(BitFnt_t));
		if(font->bitmap_font == NULL){
            BAG_DBG_LibMsg(BUFFER_FAILED_MSG, sizeof(BitFnt_t), "BMP Font");
			return ERR_END;
        }
	}

	font->loadFont = (void*)&BAG_BitText_LoadFont;
	font->unloadFont = (void*)&BAG_BitText_UnloadFont;
	font->drawChar = (void*)&BAG_BitText_DrawBitChar;
	font->setRot = (void*)&BAG_BitText_SetCharMode;
	return ERR_NONE;
}








/*
u16 _BAG_Text_GetColStr(char *text, s16 *difference)
{
	//check s8acters to ensure proper tag is identified
	if( (*text++) == '~' && (*text++)  == 'C' )
	{
		//checks to see if color is formatted properly
		if(*text++ == '[' )
		{
			int i = 0;
			s16 diff = 3;//stores the number of s8acters for stripping later
			char col[8];//stores the individual digits of the color
			
			//scans all the numbers up until the ]
			while((*text) != ']' )
			{
				col[ i++ ] = (char)*text++;
				diff++;
			}
			
			//return the number of s8acters to displace in the string
			(*difference) = diff + 1;
			//return the new color (from 16 bit value)
			return atoi(col);		
		}	
	}

	//no change
	(*difference) = 0;
	return 1;
}
*/
