#include <cstdlib>
#include <iostream>
#include <string>
#include <SDL/SDL.h>

#include <SDL/SDL_ttf.h>

#include "transform.h"

int main ( int argc, char** argv )
{
    /// [1] Démarrage
    // [1.1] Démarrages SDL et TTF
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 || TTF_Init() < 0 )
    {
        std::cout << "Impossible d'initialiser la SDL: " << SDL_GetError() << std::endl;
        std::cout << "Ou problème de TTf: " << TTF_GetError() << std::endl;
        return 1;
    }

    // [1.2] Préparation de fermeture
    atexit(SDL_Quit);
    atexit(TTF_Quit);

    // [1.3] Para-fenêtre
    SDL_WM_SetCaption("Gestion du texte avec SDL_ttf", 0);

    /// [2] Préparation des composants
    // [2.1] Préparation de la fenêtre
    SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16,
                                           SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    // [2.2] Préparation d'image(s)
    SDL_Surface *texte(0);
    SDL_Rect position;

    SDL_Surface *titre(0);

    // [2.3] Préparation du texte
    TTF_Font *police(0);
    police = TTF_OpenFont("Polices/droid.ttf",65);
    SDL_Color couleurNoire = {0,0,0};
    std::string chaine("Shtroumf aromatise !");

    titre = transform("Biliplop !!!",62);

    /// [3] Boucle principale
    bool done = false;
    while (!done)
    {
        // [3.1] Gestion évènements
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            switch (event.type)
            {
            case SDL_QUIT:
                done = true;
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    done = true;
                break;
            } // end switch event type
        } // end of message processing

        // [3.2] Calculs
        texte = TTF_RenderText_Blended(police, chaine.c_str(),couleurNoire);

        // [3.3] Dessin des composants
        SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 255, 255, 255));

        position.x = screen->w/2 - texte->w/2;
        position.y = screen->h/2 - texte->h/2;
        SDL_BlitSurface(texte, NULL, screen, &position);
        position.x = screen->w/2 - titre->w/2;
        position.y = 400;
        SDL_BlitSurface(titre, NULL, screen, &position);

        SDL_Flip(screen);
    } //fin bcl principale

    ///[4] Destruction des composants
    TTF_CloseFont(police);
    SDL_FreeSurface(texte);
    SDL_FreeSurface(titre);

    std::cout << "Aucune erreur détectée." << std::endl;
    return 0;
}