#include "font.h"
#include "draw.h"
#include "file.h"
#include <stdlib.h>

namespace font
{
    SDL_Texture *surf {nullptr};
    char spaces[127];
    int pos = 30;
    int chars_per_line = 0;

    void load(const char* filename)
    {
        char font_filename[256];
        strcpy(font_filename, filename);
        strcat(font_filename, ".txt");

        int filesize;
        char *buffer = file::getFileBuffer(font_filename, filesize, true);
        char *p = buffer;

        pos = 30;
        bool eof = false;
        while (true) {
            if (*p=='#') while (*p!=0 && *p!=10) p++;
            if (*p==0) break; while (*p==10 || *p==13) p++;
            spaces[pos++] = (*p)-48;
            if (pos==127) break;
            p++;
            if (*p==0) break; while (*p==10 || *p==13) p++;
        }
        free(buffer);

        char gif_filename[256];
        strcpy(gif_filename, filename);
        strcat(gif_filename, ".gif");
        surf = draw::loadSurface(gif_filename, 0);
    }

    void printChar(const char c, int x, int y)
    {
        const int w = spaces[30];
        const int h = spaces[31];
        const int chars_per_line = (surf->w/w);
        const int sx = ((c-32) % chars_per_line)*8;
        const int sy = ((c-32) / chars_per_line)*8;
        //printf("char %i, sx:%i, sy:%i\n", c, sx, sy);
        draw::draw({sx, sy, spaces[c], h}, {x, y, spaces[c], h});
    }

    void print(const char* text, int x, int y)
    {
        draw::setSource(surf);
        while(*text) {
            printChar(*text, x, y);
            x += spaces[*text]+1;
            text++;
        }
    }

    const int len(const char *text)
    {
        int l = 0;
        while (*text) {
            l += spaces[*text]+1;
            text++;
        }
        return l-1;
    }
}
