#include <iostream>
#include <SDL/SDL.h>
#undef main
#include "Client.h"

struct Attributs
{
    int x;
    int y;
};

int main ( int argc, char** argv )
{
    /// [1] Démarrage
    // [1.1] Démarrages SDL
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0)
    {
        std::cout << "Impossible d'initialiser la SDL: " << SDL_GetError() << std::endl;
        return 1;
    }

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

    // [1.3] Para-fenêtre
    SDL_WM_SetCaption("Points en réseau", 0);

    /// [2] Préparation des composants
    // [2.1] Préparation du réseau
    Client lan("192.168.1.87", 7856);
    if (!lan.rendreUtilisable())
    {
        std::cout << "Problème d'initialisation des connexions." << std::endl;
        return 1;
    }

    // [2.2] Préparation de la fenêtre
    SDL_Surface* screen = SDL_SetVideoMode(640, 480, 32,
                                           SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen )
    {
        std::cout << "Unable to set 640x480 video: " << SDL_GetError() << std::endl;
        return 1;
    }

    // [2.3] Préparation des points
    Attributs blocMoi;
    SDL_Rect posMoi;
    Attributs blocAutre;
    SDL_Rect posAutre;
    blocMoi.x = blocMoi.y = blocAutre.x = blocAutre.y = 100;
    SDL_Surface* imgMoi = SDL_CreateRGBSurface(SDL_HWSURFACE, 20, 20, 32, 0, 0, 0, 0);
    SDL_Surface* imgAutre = SDL_CreateRGBSurface(SDL_HWSURFACE, 20, 20, 32, 0, 0, 0, 0);
    SDL_FillRect(imgMoi, 0, SDL_MapRGB(imgMoi->format, 0, 0, 200));
    SDL_FillRect(imgAutre, 0, SDL_MapRGB(imgMoi->format, 200, 0, 0));

    /// [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;
            case SDL_MOUSEMOTION:
                blocMoi.x = event.motion.x;
                blocMoi.y = event.motion.y;
                break;
            } // end switch event type
        } // end of message processing

        // [3.2] Réseau
        lan.envoyer(&blocMoi, sizeof(Attributs));
        lan.recevoir(&blocAutre, sizeof(Attributs));

        // [3.3] Calculs
        posMoi.x = blocMoi.x;
        posMoi.y = blocMoi.y;
        posAutre.x = blocAutre.x;
        posAutre.y = blocAutre.y;

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

        SDL_BlitSurface(imgAutre, 0, screen, &posAutre);
        SDL_BlitSurface(imgMoi, 0, screen, &posMoi);

        SDL_Flip(screen);
    } //fin bcl principale

    ///[4] Destruction des composants
    SDL_FreeSurface(screen);


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