#include <string.h>
#include "allegro.h"
#include "gameConstants.h"

#include "Battle.h"
#include "Config.h"
#include "Loader.h"
#include "MusicSound.h"
#include "StartGameConfig.h"

#include <alogg/alogg.h>
#include <string>
using namespace std;

int gameMode = modeConfig;
int retVal = mainMenuContinue;
//store all major objects here
Battle * b;
Config * c;
Loader * l;
MusicSound * ms;
GameSettings * gs;
InputObj * iO;

void playMode ();
void modeSwitch ();
int initObj ();

int initObj ()
{
  b = new Battle ();
  c = new Config ();
  l = new Loader ();
  iO = new InputObj ();
  ms = new MusicSound ();

  //tells Config to set up settings
  gs = new GameSettings ();
  if (gs -> init (iO, ms, c -> sgc) != 0)
    {
      allegro_message ("Could not retrieve settings. Defaults will be used.\n");
    }

  if (c -> initialize (gs, iO, ms, l) != 0)
    {
      allegro_message ("Initialize error!\n");
      return -1;
    }

  ms -> initAudio ();

  b -> setGameSettings (gs);
  b -> setMusicSound (ms);
  b -> setInputObj (iO);
  return 0;
}

void playMode ()
{
  //plays either Config or Battle, depending on mode.

  while (retVal != mainMenuQuit && retVal != mainMenuStopMode)
    {
      if (gameMode == modeConfig)
	retVal = c -> configLoop ();
      else if (gameMode == modeBattle)
	{
	  retVal = b -> battleLoop (c -> sgc -> getCampName (), c -> sgc -> getCharName (), l);
	}
    }
}

void modeSwitch ()
{
  //after playMode exits, switch the modes
  if (gameMode == modeBattle)
    {
      gameMode = modeConfig;
      retVal = mainMenuContinue;
    }
  else if (gameMode == modeConfig)
    {
      gameMode = modeBattle;
      retVal = mainMenuContinue;
    }
}

int main(void)
{
  //1) tell config to set up settings
  //2) start config object. It will either return a signal to start the game or quit the game.
  //3) If it is told to begin battle, main loads battle with the correct parameters.
  //4) If it's told to quit, game quits.

  srand (time (NULL));

  if (allegro_init() != 0)
    return 1;

  install_keyboard();
  install_timer();
  install_mouse();

  if (initObj () != 0)
    allegro_message ("Something failed while initializing. TASM will now exit.\n");

  while (retVal != mainMenuQuit)
    {
      playMode ();
      if (retVal != mainMenuQuit)
	modeSwitch ();
    }

  return 0;
}
END_OF_MAIN(); //allegro needs it!!!
