/*!
 * @file GameEngine.cpp
 * @brief ゲームエンジンの実装
 * @date 2013/12/17
 * @author Deskull
 * 2014 Sikabane Works.
 */

#pragma once

#include "stdafx.h"
#include "GameEngine.h"


namespace Deeangband
{
	GameEngine::GameEngine()
	{
		gameWorld = new GameWorld();
		gameSurface = new GameSurfaceSDL(gameWorld);
		gameLogger = new GameLogger();

		gameSurface->SetField(gameWorld->GetField(0));
		gameSurface->SetSideStatusCreature(gameWorld->GetCreature(0));
		this->gameLogger->PutLog("GameEngine開始");
		Direction::Initialize();
	}

	PLAY_EXIT_CODE GameEngine::PlayLoop(void)
	{
		GAME_COMMAND commandID;
		PLAY_EXIT_CODE code = PLAY_EXIT_NONE;
		gameSurface->Redraw();

		while(code == PLAY_EXIT_NONE)
		{
			commandID = gameSurface->GetCommand();
			code = DoGameCommand(commandID);
		}

		return PLAY_EXIT_QUIT;
	}

	PLAY_EXIT_CODE GameEngine::DoGameCommand(GAME_COMMAND command)
	{
		Creature *playerPtr = gameWorld->GetPlayerCreature();

		switch(command)
		{
		case GAME_COMMAND_VIEW_PLAYER_STATUS:
			gameSurface->ViewCreatureStatus(gameWorld->GetCreature(0));
			break;
		case GAME_COMMAND_REDRAW:
			gameSurface->Redraw();
			break;
		case GAME_COMMAND_DEBUG_XML_SAVE:
			gameWorld->XMLSave();
			gameSurface->SystemMessage("XMLに保存しました。");
			break;
		case GAME_COMMAND_DEBUG_XML_LOAD:
			gameSurface->Redraw();
			gameWorld->XMLLoad();
			gameSurface->SystemMessage("XMLから呼び出しました。");
			break;
		case GAME_COMMAND_EXIT:
			return PLAY_EXIT_QUIT;
			break;
		case GAME_COMMAND_NORTH:
			this->WalkCreature(playerPtr, DIRECTION_NORTH);
			break;
		case GAME_COMMAND_NORTH_EAST:
			this->WalkCreature(playerPtr, DIRECTION_NORTH_EAST);
			break;
		case GAME_COMMAND_EAST:
			this->WalkCreature(playerPtr, DIRECTION_EAST);
			break;
		case GAME_COMMAND_SOUTH_EAST:
			this->WalkCreature(playerPtr, DIRECTION_SOUTH_EAST);
			break;
		case GAME_COMMAND_SOUTH:
			this->WalkCreature(playerPtr, DIRECTION_SOUTH);
			break;
		case GAME_COMMAND_SOUTH_WEST:
			this->WalkCreature(playerPtr, DIRECTION_SOUTH_WEST);
			break;
		case GAME_COMMAND_WEST:
			this->WalkCreature(playerPtr, DIRECTION_WEST);
			break;
		case GAME_COMMAND_NORTH_WEST:
			this->WalkCreature(playerPtr, DIRECTION_NORTH_WEST);
			break;
		}
		return PLAY_EXIT_NONE;
	}

	bool GameEngine::WalkCreature(Creature *creaturePtr, DIRECTION direction)
	{
		if(gameWorld->GetCreatureFromPosition(creaturePtr->GetFieldID(), &(creaturePtr->GetPosition() + Direction::DirectionVector[direction])) != NULL)
		{
			return false;
		}
		creaturePtr->Walk(this->gameLogger, direction);
		return true;
	}

}
