/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#include "gameapp.h"
#include "physics.h"
#include "renderer.h"
#include "eventhandler.h"
#include "glscreen.h"
#include "mainmenu.h"
#include "lcd.h"
#include "options.h"
#include "besttimes.h"
#include "sound.h"
#include "credits.h"
#include <boost/lexical_cast.hpp>

GameApp GameApp::m_instance;

void GameApp::init(int argc, char* argv[])
{
	readParams(argc, argv);
	m_options = new Options("kuula.cfg");
	initVideo();
	LCD::load("alpha.lcd");
	m_renderer = new Renderer();
	m_physics = new Physics();
	m_events = new EventHandler(*m_physics, *m_renderer);
	BestTimes::getInstance().load("times.dat");
	Sound& snd = Sound::getInstance();
	snd.init("music/menu_intro.ogg", "music/menu.ogg", "music/game.ogg");
	std::string& musicState = (*m_options)["music"];
	if (!musicState.empty() && musicState[0] != '1')
		snd.setState(0);
	snd.playMenu();
	
	std::string& msensitivity((*m_options)["msensitivity"]);
	if (!msensitivity.empty())
	m_events->setMouseSensitivity(boost::lexical_cast<float>(msensitivity));
	std::string& jsensitivity((*m_options)["jsensitivity"]);
	if (!jsensitivity.empty())
		m_events->setJoystickSensitivity(boost::lexical_cast<float>(jsensitivity));

	std::string& turnBoard((*m_options)["turnboard"]);
	if (!turnBoard.empty())
		m_renderer->turnBoard = turnBoard[0]=='0' ? 0 : 1;

	std::string& topView((*m_options)["topview"]);
	if (!topView.empty())
		m_renderer->topView = topView[0]=='0' ? 0 : 1;
	
	m_menu = new MainMenu();
}

void GameApp::start()
{
	m_menu->exec();
	Credits credits;
	credits.exec();
}

void GameApp::readParams(int argc, char* argv[])
{
	(void)argc;
	(void)argv;
}

void GameApp::initVideo()
{
	Options& opts = *m_options;
	int resX = atoi(opts["res_x"].c_str());
	int resY = atoi(opts["res_y"].c_str());
	bool fullscreen = atoi(opts["fullscreen"].c_str());
	if (!resX || !resY)
		GLScreen::init(fullscreen);
	else
		GLScreen::init(resX, resY, fullscreen);
}
