#include <SDL.h>
#include <SDL_events.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include <SDL_thread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sdlame.h"
#include "vars.h"

#include <kos.h>
#include <SDL_dreamcast.h>


extern uint8 romdisk[];

KOS_INIT_FLAGS(INIT_DEFAULT | INIT_MALLOCSTATS);
KOS_INIT_ROMDISK(romdisk);

int main(int argc, char *argv[])
{
  printf("Starting...\n");
  int exit = 0;

  /* Initialize SDL */
  //SDL_INIT_EVENTTHREAD makes not working dreamcast joystick!!!
  SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK|SDL_INIT_TIMER);
  printf("SDL Iniciado\n");
  
  SDL_DC_MapKey(0,SDL_DC_X,SDLK_1);
  SDL_DC_MapKey(0,SDL_DC_START,SDLK_1);
  
  SDL_DC_MapKey(0,SDL_DC_Y,SDLK_n); //X button, change player
  SDL_DC_MapKey(0,SDL_DC_B,SDLK_SPACE); //selects the piece!
  SDL_DC_MapKey(0,SDL_DC_A,SDLK_RETURN); //Start, Move the piece!
  SDL_DC_MapKey(0,SDL_DC_R,SDLK_ESCAPE); //left button on the controller
  SDL_DC_MapKey(0,SDL_DC_UP,SDLK_UP); 
  SDL_DC_MapKey(0,SDL_DC_DOWN,SDLK_DOWN); 
  SDL_DC_MapKey(0,SDL_DC_LEFT,SDLK_LEFT); 
  SDL_DC_MapKey(0,SDL_DC_RIGHT,SDLK_RIGHT); 
	
  SDL_JoystickEventState(SDL_ENABLE);
  SDL_JoystickOpen(0);
  SDL_ShowCursor(0);
  
  /* Initialize the Font and Screen */
  if(argc == 2)
  {
    screen_width = 320; //is set to 800 in the next step
  }

  switch_resolution();
  printf("Resolucion aplicada\n");

  /* Load Font Module */
  TTF_Init();
  font_size = 16;
  font = TTF_OpenFont("rd/img/320x240/font.ttf", font_size);
  printf("TTF Iniciado\n");
  
  /* Set Title for Window Managers */
  //SDL_WM_SetCaption("SdLame", "SdLame");

  /* Set Icon for Window Managers */
  //SDL_WM_SetIcon(SDL_LoadBMP("img/icon.bmp"), NULL);

  /* Printf Version */
  VERSION;

  /* Draw Background */
  background(1);
  printf("Dibujado fondo\n");
  /* Update Screen */
  SDL_Flip(screen);
  printf("Pantalla actualizada\n");

  /* Loop, while Start is not pressed */
  key_loop();
  printf("Despues del keyloop\n");

  /* Set Menu Position to one, because it's unset before */
  menu_position = 1;

  /* Set Mode to Multi Player by default */
  mode = 2;

  /* Create a new Game */
  new_game();
  printf("Nuevo juego creado\n");
  /* Draw Menu to Display */
  menu();
  printf("Menu finalizado\n");

  while(exit != 1)
  {
    if(player == 1)
    {
      turn_player_1();
    }
    else
    {
      if(mode == 1)
      {
        turn_computer();
      }
      else if(mode == 2)
      {
        turn_player_2();
      }
    }
  }

  menu();
  nexit();
  return 1;
}
