#include <allegro.h>
#include <stdio.h>
#include <time.h>
#include "fudgefont.h"

#ifdef ALLEGROGL
#include <alleggl.h>
#endif

int main(void)
{
    srand(time(NULL));

    allegro_init();
    set_color_depth(32);

    int mode;
#ifdef ALLEGROGL
    mode = GFX_OPENGL_WINDOWED;
    install_allegro_gl();
#else
    mode = GFX_AUTODETECT_WINDOWED;
#endif

    set_gfx_mode(mode, 640, 480, 0, 0);
    install_keyboard();
    install_timer();

    install_fudgefont();

    /* Load 16 fonts with different sizes. */
    FONT *f[16];
    int i;
    for (i = 0; i < 16; i++)
    {
        int size = 8 + i * 2;
        PALETTE pal;
        f[i] = load_font("ttf/DejaVuSans.ttf", pal, &size);
        select_palette(pal);
#ifdef ALLEGROGL
        /* If we have AllegroGL, we set up AllegroGL alpha fonts. */
        FONT *temp = f[i];
        f[i] = allegro_gl_convert_allegro_font_ex(temp, AGL_FONT_TYPE_TEXTURED,
            -1, GL_ALPHA8);
        destroy_font(temp);
#endif
    }

    #ifdef ALLEGROGL
        allegro_gl_set_allegro_mode();
    #endif

    int unicode = '*';

    while (1)
    {
        clear_to_color(screen, makecol(0, 0, 0));

        char str[16];
        ustrzcpy(str, 16, "");
        uinsert(str, 0, unicode);
        for (i = 0; i < 100; i++)
        {
            int x = rand() % 640;
            int y = rand() % 480;
            int size = rand() % 16;
            char const *texts[] = {
                str,
                "FudgeFont",
#ifdef ALLEGROGL
                "AllegroGL"
#else
                "Allegro"
#endif
            };

            char const * str = texts[rand() % (sizeof(texts) / sizeof(texts[0]))];

#ifdef ALLEGROGL
            glEnable(GL_TEXTURE_2D);
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glColor3ub(rand() & 255, rand() & 255, rand() & 255);
            int tl = text_length(f[size], str);
            allegro_gl_printf_ex(f[size], x - tl / 2, y, 0, "%s", str);
#else
            fudgefont_color_range(0, 0, 0, rand() & 255, rand() & 255,rand() & 255);
            textprintf_centre_ex(screen, f[size], x, y, -1, -1, "%s", str);
#endif
        }

#ifdef ALLEGROGL
            allegro_gl_flip();
#endif

        unicode = ureadkey(NULL);
        if (unicode == 27)
            break;
    }

    return 0;
}
