/*
    Bazoo_worms the game
    Copyright (C) 2011  Pavel Prochazka

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "MG_lib.h"
#include "WRMS_include.h"
#include "stages.h"

static WRMS_STAGES _current_stage = STAGE_INITIAL;
static WRMS_STAGES _stage_request = STAGE_INITIAL;
static void *_stage_args = NULL;

void
WRMS_stage_set_args (void *arg)
{
  _stage_args = arg;
}

WRMS_STAGES
WRMS_stage ()
{
  return _current_stage;
}

static void
init_animations ()
{
  SDL_Rect r = { 0, 0, 32, 32 };

  MG_make_animation ("worm_moving_right", 8, 180, &r);
  MG_make_animation ("worm_moving_left", 8, 180, &r);
}

static int
build_ingame (NODE * args)
{
  init_animations ();

  if (WRMS_load_map (NULL) < 0)
    {
      printf ("warn: map could not been loaded ... returning to menu!\n");
      WRMS_enter_stage (STAGE_MENU);
      MG_drawing_stack_free ();
      return -1;
    }

  MG_set_environment_physics (ENV_PHYSICS);
  WRMS_game_begin (args, 0);

  return 0;
}

static void *
WRMS_build_implicit_stage (WRMS_STAGES stage)
{
  switch (stage)
    {
    case STAGE_INGAME:
      build_ingame (_stage_args);
      break;
    case STAGE_MENU:
      WRMS_menu_enter (_stage_args);
      break;
    default:
      printf ("Default stage...quiting\n");
      break;
    }

  return MG_drawing_stack ();
}

int
WRMS_enter_stage (WRMS_STAGES stage)
{
  return (_stage_request = stage);
}

int
WRMS_check_stages ()
{
  if (_current_stage != _stage_request)
    {
      _current_stage = _stage_request;
      MG_drawing_stack_free ();

      WRMS_build_implicit_stage (_current_stage);
      _stage_args = NULL;
    }
  return 0;
}
