/*
 * Application.cpp
 *
 *  Created on: 14.01.2011
 *      Author: gmueller
 */

#include "Application.h"
#include "Time.h"
#include "Network.h"

#include <iostream>

Application::Application() :
	running(false), master(false), time(0.0), network(&game) {

}

Application::~Application() {

}

bool Application::isRunning() {
	return running;
}

void Application::start() {
	std::cout << "[Application] start" << std::endl;
	running = true;
}

void Application::stop() {
	std::cout << "[Application] stop" << std::endl;
	running = false;
}

void Application::initialize(Arguments &arg) {
	std::cout << "[Application] initialize" << std::endl;

	// setup time
	PerformanceTimer::set(0.0);
	time = PerformanceTimer::get();

	// setup game
	game_setup(&game);
	game_reset(&game);

	// setup schedules
	gameUpdateSchudule.setExact(true);
	gameUpdateSchudule.setInterval(0.05);

	std::string host = arg.getString("-h", std::string());
	network.initialize(host);

	// setup network
	if (host.empty()) {
		setMaster(true);
	} else {
		setMaster(true);
	}

	// start
	start();
}

void Application::shutdown() {
	std::cout << "[Application] shutdown" << std::endl;

	network.shutdown();
}

void Application::update() {
	// update time values
	time = PerformanceTimer::get();
	dt = time - lastTime;
	lastTime = time;

	// network stuff
	network.service(master ? 1 : 0);
	game_update(&game, dt);
	if (master && gameUpdateSchudule.next(time)) {
		network.sendGameUpdates();
	}
}

void Application::setMaster(bool master) {
	std::cout << "[Application] setMaster = " << master << std::endl;

	this->master = master;
	game_set_master(&game, master ? 1 : 0);
}
