#include "maze.h"

bool choose_orientation(int width, int heigth)
{
  return width < heigth;
}

void wait_key(void)
{
  SDL_Event event;
 
  do
    SDL_WaitEvent(&event);
  while (event.type != SDL_QUIT && event.type != SDL_KEYDOWN);
}


void rec_divide(SDL_Surface *image, SDL_Surface *display,
                int x, int y, int width, int heigth, bool orientation,
                int size)
{
  update_display(image, display);


  if(width <= 2 || heigth <= 2)
    return;
  
  // Début du mur
  int wx = x + (orientation ? 0 : rand()%(width - 2) + 1);
  int wy = y + (orientation ? rand()%(heigth - 2) + 1: 0);

  // Passage dans le mur
  int px = wx + (orientation ? rand()%width: 0);
  int py = wy + (orientation ? 0 : rand()%heigth);

  // direction du dessin du mur
  int dx = orientation ? 1 : 0;
  int dy = orientation ? 0 : 1;

  // longeur du mur
  int length = orientation ? width: heigth;
  for(int i = 0; i < length; ++i)
  {
    if(wx != px || wy != py)
      draw_cell(image, wx, wy, size, orientation);
    wx += dx;
    wy += dy;
  }
  int w;
  int h;
  int nx = x;
  int ny = y;
  if(orientation)
  {
    w = width;
    h = wy-y;
  }
  else
  {
    w = wx-x;
    h = heigth;
  }
  rec_divide(image, display, nx, ny, w, h, choose_orientation(w, h), size);


  if(orientation)
  {
    nx = x;
    ny = wy;
    w = width;
    h = y+heigth-wy;
  }
  else
  {
    nx = wx;
    ny = y;
    w = x+width-wx;
    h = heigth;
  }
  rec_divide(image, display, nx, ny, w, h, choose_orientation(w, h), size);
  
}

void create_maze(int width, int heigth, int size_cell, string filename)
{
  init_SDL();
  SDL_Surface *image = create_image(width*size_cell, heigth*size_cell);
  white_image(image);
  SDL_Surface *display = init_display(image, filename);
  update_display(image, display);
  srand(time(NULL));
  rec_divide(image, display, 0, 0, width, heigth,
         choose_orientation(width, heigth), size_cell);
  save_image(image, filename);
  wait_key();
  
  
}

