/*=============================================================================
Exemple SDL
===============================================================================
Preprocesseur
=============================================================================*/
#include "sdl/SDL.h"

#include <fstream>
#include <iostream>


#include "doddle.hpp"

using namespace std;

int main(int argc, char * argv[])
{

    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface *screen = SDL_SetVideoMode(600, 400, 8, SDL_SWSURFACE);
    SDL_Event event;

    int keypress = 0,
        mx = 0,
        my = 0,
        mb = 0,
        dx = 0,
        dy = 0,
        mt = 0;
        
    Uint32 brown = SDL_MapRGB( screen->format, 0x66, 0x33, 0x00 ),
           red = SDL_MapRGB( screen->format, 0xFF, 0x00, 0x00 ),
           black = SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 );
           
    doddle roots;
    roots.init(300,100);
           
    while(!keypress)
    {
        SDL_Flip(screen);
        SDL_FillRect(screen,0,brown);

        while(SDL_PollEvent(&event))
        {
            switch (event.type)
            {
                case SDL_QUIT:
                    keypress = 1;
                    break;
                case SDL_KEYDOWN:
                    keypress = 1;
                    break;
                case SDL_MOUSEMOTION:
                    mx = event.motion.x;
                    my = event.motion.y;
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    if (roots.isTouch())
                        mb = 1;
                    break;
                case SDL_MOUSEBUTTONUP:
                    mb = 0;
                    roots.unTouch();
                    break;
            }
        }

        roots.reset();
        while (!roots.end())
        {
            roots.parse();

            SDL_Rect tmp = {roots.x(), roots.y(),8,8};
            
            if (tmp.x<mx && tmp.x+tmp.w>mx && tmp.y<my && tmp.y+tmp.h>my )
            {
                roots.touch();
                SDL_FillRect(screen, &tmp, red);
            }
            else if (mb && roots.atTouch())
            {
                if (pow((float)mx-roots.x(),2)+pow((float)my-roots.y(),2)<400)
                    SDL_FillRect(screen, &tmp, red);
                else
                {
                    roots.pathTo(mx,my);
                }
            }
            else
            {
                SDL_FillRect(screen, &tmp, black);
            }
            
            roots.next();
        }


    }
    SDL_Quit();
    return 0;
}