#include <QtGui/QWidget>
#include <QtGui/QLabel>
#include <vector>
#include "MainWindow.h"
#include "softProj\ChatWidget\ChatWidget.h"
#include "softProj\ChatWidget\ChatMessage.h"
#include "softProj\ScienceTreeWidget\ScienceTreeWidget.h"
#include "softProj\DetailsWidget\ComplexItem.h"
#include "softProj\ChatWidget\IncomingWidget.h"
#include "softProj\DetailsWidget\SimpleItem.h"
#include "softProj\TradeWidget\TradeWidget.h"
#include "softProj\NavigationWidget\navigationwidget.h"
#include "softProj\DevicesWidget\allDevicesWidget.h"
#include "softProj\LoginWidget\LoginWidget.h"
#include "softProj\helpers.h"
#include "softProj\clientServer\threads.h"
#include "styles.h"
#include "softProj\settings.h"
#include "math\SupportFunctions.h"
#include "console/InputRegister.h"
#include "../streams/ErrorStream.h"
#include <cstdlib>
#include <cassert>

#include <qpixmap.h>
#include "gameSettings.h"

extern KODIAK_DEBUG_STREAM KODIAK_DEBUG_COUT;

void MainWindow::updateShipSection() {

	if (!currentState_.shipSectionState.hasCurrentShip()) {
		detailsWidget_->hideDetailsPanel();
		return;
	}

	ShipSectionState shipSectionState = currentState_.shipSectionState;

	switch (shipSectionState.state) {
		case SHIP_NAVIGATION:
			setActivity(L"Navigace lodi");
			commandClient_->navigationStatus(shipSectionState.getCurrentShipId());
			commandClient_->shipJourneyDetails(shipSectionState.getCurrentShipId());
			detailsWidget_->showNavigation();
			break;

		case SHIP_ENERGY_CIRCUIT:
			setActivity(L"Energetický okruh lodi");
			commandClient_->updateDeviceEnergyState(shipSectionState.getCurrentShipId());
			detailsWidget_->showDevices();
			break;

		case SHIP_WEAPONS:
			setActivity(L"Zbraňový okruh lodi");
			commandClient_->updateFortressWeaponsInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showWeapons();
			break;

		case SHIP_SHIELDS:
			setActivity(L"Štíty");
			commandClient_->updateFortressShieldsInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showShields();
			break;

		case SHIP_RENDER:
			setActivity(L"Model");
			renderWidgetSmall->setVisible(true);
			activateModelViewerSlot();
			showSmallRenderPanel(shipSectionState.getCurrentShip());
			break;

		case SHIP_CENTRAL_INFORMATION:
			setActivity(L"Centrální informace lodi");
			commandClient_->updateFortressCentralInformation(shipSectionState.getCurrentShipId());		
			detailsWidget_->showCentralInfo();
			break;

		case SHIP_NAVIGATION_COMPUTER:
			setActivity(L"Počítač");
			commandClient_->updateFortressMainframeInformation(shipSectionState.getCurrentShipId());		
			detailsWidget_->showMainframe();
			break;

		case SHIP_IMPULSE_DRIVE:
			setActivity(L"Impulzní pohon");
			commandClient_->updateShipImpulsDriveInformation(shipSectionState.getCurrentShipId());		
			detailsWidget_->showImpulsDrive();
			break;

		case SHIP_SUBSPACE_DRIVE:
			setActivity(L"Podprostorový pohon");
			commandClient_->updateShipSubspaceDriveInformation(shipSectionState.getCurrentShipId());		
			detailsWidget_->showSubspaceDrive();
			break;

		case SHIP_CREW:
			setActivity(L"Posádka");
			commandClient_->updateFortressCrewInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showCrew();
			break;

		case SHIP_QUARRYING:
			setActivity(L"Těžba");
			commandClient_->updateFortressQuarryInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showQuarrying();
			break;

		case SHIP_UBICATION:
			setActivity(L"Ubikace");
			commandClient_->updateFortressAccommodationsInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showAccommodations();
			break;

		case SHIP_STOCK:
			setActivity(L"Sklady");
			commandClient_->updateFortressWarehousesInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showWarehouses();
			break;

		case SHIP_ANDROIDS:
			setActivity(L"Androidi");
			commandClient_->updateShipAndroidsInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showAndroids();
			break;

		case SHIP_EQUIPMENT:
			setActivity(L"Vybavení");
			commandClient_->updateFortressOtherEquipmentInformation(shipSectionState.getCurrentShipId());
			detailsWidget_->showOtherEquipment();
			break;

		case SHIP_MASKING:
			detailsWidget_->showCloaking();
			commandClient_->updateFortressCloakingInformation(shipSectionState.getCurrentShipId());
			break;

		case SHIP_SENSORS:
			detailsWidget_->showSensors();
			commandClient_->updateFortressSensorsInformation(shipSectionState.getCurrentShipId());
			break;

		case SHIP_NONE:
			detailsWidget_->hideDetailsPanel();
			break;
	}
}

void MainWindow::updateBaseSection() {
	if (!currentState_.baseSectionState.hasCurrentBase()) {
		detailsWidget_->hideDetailsPanel();
		return;
	}

	BaseSectionState baseSectionState = currentState_.baseSectionState;

	switch (baseSectionState.state) {
		case BASE_ENERGY_CIRCUIT:
			setActivity(L"Energetický okruh lodi");
			commandClient_->updateDeviceEnergyState(baseSectionState.getCurrentBaseId());
			detailsWidget_->showDevices();
			break;

		case BASE_WEAPONS:
			setActivity(L"Zbraňový okruh lodi");
			commandClient_->updateFortressWeaponsInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showWeapons();
			break;

		case BASE_SHIELDS:
			setActivity(L"Štíty");
			commandClient_->updateFortressShieldsInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showShields();
			break;

		case BASE_RENDER:
			setActivity(L"Model");
			renderWidgetSmall->setVisible(true);
			this->activatePlanetViewerSlot();
			showSmallRenderPanel(baseSectionState.getCurrentBase());
			break;

		case BASE_CENTRAL_INFORMATION:
			setActivity(L"Centrální informace lodi");
			commandClient_->updateFortressCentralInformation(baseSectionState.getCurrentBaseId());		
			detailsWidget_->showCentralInfo();
			break;

		case BASE_NAVIGATION_COMPUTER:
			setActivity(L"Počítač");
			commandClient_->updateFortressMainframeInformation(baseSectionState.getCurrentBaseId());		
			detailsWidget_->showMainframe();
			break;

		case BASE_CREW:
			setActivity(L"Posádka");
			commandClient_->updateFortressCrewInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showCrew();
			break;

		case BASE_QUARRYING:
			setActivity(L"Těžba");
			commandClient_->updateFortressQuarryInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showQuarrying();
			break;

		case BASE_UBICATION:
			setActivity(L"Ubikace");
			commandClient_->updateFortressAccommodationsInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showAccommodations();
			break;

		case BASE_STOCK:
			setActivity(L"Sklady");
			commandClient_->updateFortressWarehousesInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showWarehouses();
			break;

		case BASE_ANDROIDS:
			setActivity(L"Androidi");
			commandClient_->updateBaseAndroidsInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showAndroids();
			break;

		case BASE_EQUIPMENT:
			setActivity(L"Vybavení");
			commandClient_->updateFortressOtherEquipmentInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showOtherEquipment();
			break;

		case BASE_HANGARS:
			setActivity(L"Hangáry");
			commandClient_->updateBaseHangarsInformation(
				baseSectionState.getCurrentBaseId(),
				detailsWidget_->ui_.hangarWidget->getSelectedHangarID(),
				detailsWidget_->ui_.hangarWidget->getSelectedPatternName());
			detailsWidget_->showHangar();
			break;

		case BASE_FACTORIES:
			setActivity(L"Továrny");
			commandClient_->updateBaseFactoriesInformation(baseSectionState.getCurrentBaseId());
			detailsWidget_->showFactories();
			break;

		case BASE_MASKING:
			detailsWidget_->showCloaking();
			commandClient_->updateFortressCloakingInformation(baseSectionState.getCurrentBaseId());
			break;

		case BASE_SENSORS:
			detailsWidget_->showSensors();
			commandClient_->updateFortressSensorsInformation(baseSectionState.getCurrentBaseId());
			break;

		case BASE_NONE:
			detailsWidget_->hideDetailsPanel();
			break;
	}
}

void MainWindow::changeShipSectionSlot(SimpleItem & item, EShipSectionState data)
{	
	currentState_.shipSectionState.changeState(data);
	updateShipSection();
}

void MainWindow::changeBaseSectionSlot(SimpleItem & item, EBaseSectionState data)
{	
	currentState_.baseSectionState.changeState(data);
	updateBaseSection();
}

MainWindow::MainWindow( int argc, char **argv, Environment &environment )
{
	ui_.setupUi(this);	
	
	ADMIN_LOGIN = "admin";

	ui_.shadowFrame->setVisible(false);

	this->commandClient_ = NULL;

	/* Set dialogs to NULL, because they are not createt yet */

	unmountDialog_ = NULL;	
	warningDialog_ = NULL;
	messageDialog_ = NULL;
	mountDialog_ = NULL;
	inputDialog_ = NULL;

	this->setFixedHeight( this->height() );
	this->setFixedWidth( this->width() );

	setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);

	treeWidget_ = createAndInitTree(ui_.rightMainPanel);	
	detailsWidget_ = new DetailsWidget(ui_.rightMainPanel);	
	incomingWidget_ = new IncomingWidget(ui_.incomingWidgetFrame);
	tradeWidget_ = new TradeWidget(ui_.rightMainPanel);
	fightWidget_ = new FightWidget(ui_.rightMainPanel);
	buildWidget_ = new BuildWidget(ui_.rightMainPanel);
	chatWidget_ = new ChatWidget(ui_.rightMainPanel);
	loginWidget_ = new LoginWidget(this);

	// OtherviewWidget & its selection logic ----------------------------
	otherviewWidget = new OtherviewWidget( ui_.rightMainPanel );

	const QString applicationPath = QCoreApplication::applicationDirPath()+"/";

	otherviewLogic = new SelectionLogic( *otherviewWidget );
		
	otherviewLogic->shipIcon[ type0 ].smallIcon = QIcon(  QString(  applicationPath+"../images/otherview/ship0.png") );
	otherviewLogic->shipIcon[ type0 ].bigIcon = QIcon(  QString( applicationPath+"../images/otherview/flycatcherIcon.png") );

	otherviewLogic->shipIcon[ type1 ].smallIcon = QIcon(  QString( applicationPath+"../images/otherview/ship1.png") );
	otherviewLogic->shipIcon[ type1 ].bigIcon = QIcon(  QString( applicationPath+"../images/otherview/submarineIcon.png") );

	otherviewLogic->shipIcon[ type2 ].smallIcon = QIcon(  QString( applicationPath+"../images/otherview/ship2.png") );
	otherviewLogic->shipIcon[ type2 ].bigIcon = QIcon(  QString( applicationPath+"../images/otherview/cruiserIcon.png") );

	otherviewLogic->shipIcon[ type3 ].smallIcon = QIcon(  QString( applicationPath+"../images/otherview/ship3.png") );
	otherviewLogic->shipIcon[ type3 ].bigIcon = QIcon(  QString( applicationPath+"../images/otherview/taxiIcon.png") );

	otherviewLogic->shipIcon[ type4 ].smallIcon = QIcon(  QString( applicationPath+"../images/otherview/ship4.png") );
	otherviewLogic->shipIcon[ type4].bigIcon = QIcon(  QString( applicationPath+"../images/otherview/xWingIcon.png") );

	otherviewLogic->shipIcon[ type5 ].smallIcon = QIcon(  QString( applicationPath+"../images/otherview/ship5.png") );
	otherviewLogic->shipIcon[ type5 ].bigIcon = QIcon(  QString( applicationPath+"../images/otherview/enterpriseIcon.png") );


	// OpenGLWidget -----------------------------------------------------------------------
	renderWidgetBig = new GLwidget2( ui_.rightMainPanel );
	renderWidgetBig->setGeometry( 0, 0, ui_.rightMainPanel->width(), ui_.rightMainPanel->height()- otherviewWidget->height() );
	otherviewWidget->setGeometry( 0, renderWidgetBig->height(), renderWidgetBig->width(), otherviewWidget->height() );

	renderWidgetSmall = new GLwidget2( this->detailsWidget_->ui_.modelViewPanel, renderWidgetBig);
	renderWidgetSmall->setGeometry( this->detailsWidget_->ui_.modelViewPanel->geometry() );

	// AttackWidget ----------------------------------------------------------------------
	attackWidget = new AttackWidget( this->ui_.windowFrame  );
	attackWidget->setGeometry( this->ui_.windowFrame->width() - attackWidget->width() -10 , 10,  attackWidget->width(),  attackWidget->height() );
	
	// -------------------------------------------------------------------

	Settings::instance().connectSound(ui_.showChatButton);
	Settings::instance().connectSound(ui_.showTradeButton);
	Settings::instance().connectSound(ui_.showFightButton);
	Settings::instance().connectSound(ui_.showBuildButton);
	Settings::instance().connectSound(ui_.showBasesTableButton);
	Settings::instance().connectSound(ui_.showShipsTableButton);
	Settings::instance().connectSound(ui_.showScienceTreeButton);

	connectSignals();

	//-------------------------
	//Render issues initialization
	this->sharedData = new OpenGlSharedData (  argv[0], InputSpace::getResourcePath( argv[2] ), environment );

	mapViewerApp = new MapViewerApp( "MapViewerApp", *renderWidgetBig->getContext(), *sharedData );
	mapViewerApp->setResolution( renderWidgetBig->width(), renderWidgetBig->height() );

	this->planetViewerApp = new PlanetViewerApp( "PlanetViewerApp", *renderWidgetSmall->getContext(), *sharedData );
	planetViewerApp->setResolution(  renderWidgetSmall->width(), renderWidgetSmall->height() );		

	this->modelViewerApp = new ModelViewerApp( "ModelViewerApp", *renderWidgetSmall->getContext(), *sharedData );
	this->modelViewerApp->setResolution(  renderWidgetSmall->width(), renderWidgetSmall->height() );

	this->planetViewerActive = false;
	this->modelViewerActive = false;
	this->mapViewerActive	= false;
	this->newShipSelected = false;
	this->centerAsSoonAsPossible = false;
	this->isPossibleToCenter = false;

	this->activeShipLocation.actualSpaceObject = 0;
	this->activeShipLocation.actualStar = 0;
	this->activeShipLocation.nearestStar = 0;

	this->activeShipIdSpaceMap = false;

	this->hideAllWidgets();

	currentState_.changeMainState(LOGIN);

	setGameSecondsPerActualSecond(30);
	
	showLoginPanel();

	isWaitingForUpdateFortressResponse = false;
	isThereAnotherUpdateFortressNotification = false;
}

void MainWindow::setGameSecondsPerActualSecond(unsigned long value) {
	this->detailsWidget_->ui_.accommodationsWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.androidsWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.centralInfoWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.crewWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.devicesWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.factoriesWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.hangarWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.impulsDriveWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.mainframeWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.miningWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.navigationWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.otherEquipmentWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.shieldsWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.subspaceDriveWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.warehousesWidget->setGameSecondsPerActualSecond(value);
	this->detailsWidget_->ui_.weaponsWidget->setGameSecondsPerActualSecond(value);
	this->fightWidget_->setGameSecondsPerActualSecond(value);

	ui_.speedValue->setText(Settings::instance().formatNumber(value) + " hs");
}

void MainWindow::connectSignals() {

	/* MAP */

	bool ok = true;
	ok = ok && QObject::connect( otherviewLogic, SIGNAL( attackButtonSignal(unsigned long) ), this, SLOT(getAttackListSlot(unsigned long)) );
	ok = ok && QObject::connect( otherviewLogic, SIGNAL( radarButtonSignal(unsigned long) ),  this, SLOT(getRadarDataSlot(unsigned long)) );
	ok = ok && QObject::connect( otherviewLogic, SIGNAL( settingButtonSignal(unsigned long) ),  this, SLOT(shipSettingsSlot(unsigned long)) );
	ok = ok && QObject::connect( otherviewLogic, SIGNAL( navigationButtonSignal(unsigned long) ),  this, SLOT(shipNavigationSlot(unsigned long)) );
	ok = ok && QObject::connect( otherviewLogic, SIGNAL( weaponsButtonSignal(unsigned long) ),  this, SLOT(shipWeaponsSlot(unsigned long)) );
	assert(ok && "OtherviewLogic and mainwindow connection failed!");

	ok = ok && connect(
		this->attackWidget,  SIGNAL(targetSelectionSignal(unsigned long)),
		this, SLOT(setAttackTargetSlot(unsigned long)) );

	/* FIGHT WIDGET */

	ok = ok && connect(
		fightWidget_, SIGNAL(fortressInWeaponsRangeSignal(id_t)),
		this, SLOT(fortressInWeaponsRangeSlot(id_t)));	

	ok = ok && connect(
		fightWidget_, SIGNAL(fortressWeaponsSettingsSignal(id_t)),
		this, SLOT(fortressWeaponsSettingsSlot(id_t)));	

	ok = ok && connect(
		fightWidget_, SIGNAL(attackFortressSignal(id_t, id_t)),
		this, SLOT(attackFortressSlot(id_t, id_t)));

	ok = ok && connect(
		fightWidget_, SIGNAL(stopAttackFortressSignal(id_t)),
		this, SLOT(stopAttackFortressSlot(id_t)));

	ok = ok && connect(
		fightWidget_, SIGNAL(submitWeaponsSignal(id_t, WeaponsChangeDetails &)),
		this, SLOT(submitWeaponsSlot(id_t, WeaponsChangeDetails &)));

	ok = ok && connect(
		fightWidget_, SIGNAL(resetWeaponsSignal(id_t)),
		this, SLOT(resetWeaponsSlot(id_t)));

	ok = ok && connect(
		fightWidget_, SIGNAL(updateAttackWarningsSignal(const std::map<id_t, fortress_under_attack_data> &)),
		this, SLOT(updateAttackWarningsSlot(const std::map<id_t, fortress_under_attack_data> &)));

	ok = ok && connect(
		fightWidget_, SIGNAL(removeFortressSignal(id_t, const std::string &)),
		this, SLOT(removeFortressSlot(id_t, const std::string &)));
	
	/* MAIN MENU */

	ok = ok && connect(
		ui_.showShipsTableButton,  SIGNAL(clicked()),
		this, SLOT(showShipsTableSlot())
		);

	ok = ok && connect(
		ui_.showBasesTableButton, SIGNAL(clicked()),
		this, SLOT(showBasesTableSlot())
		);

	ok = ok && connect(
		ui_.showScienceTreeButton,  SIGNAL(clicked()),
		this, SLOT(showScienceTreeSlot())
		);

	ok = ok && connect(
		ui_.showSpaceMapButton,  SIGNAL(clicked()),
		this, SLOT( showSpaceMapSlot())
		);

	ok = ok && connect(
		ui_.showChatButton,  SIGNAL(clicked()),
		this, SLOT(showChatSlot())
		);

	ok = ok && connect(
		ui_.showTradeButton,  SIGNAL(clicked()),
		this, SLOT(showTradeSlot())
		);

	ok = ok && connect(
		ui_.showFightButton,  SIGNAL(clicked()),
		this, SLOT(showFightSlot())
		);

	ok = ok && connect(
		ui_.showBuildButton, SIGNAL(clicked()),
		this, SLOT(showBuildSlot())
		);

	/* CHAT */

	ok = ok && QObject::connect(
		chatWidget_, SIGNAL(sendChatMessageSignal(ChatMessage *)),
		this, SLOT(sendChatMessageSlot(ChatMessage *)));

	ok = ok && QObject::connect(
		chatWidget_, SIGNAL(unreadChatMessageSignal(ChatMessage *)),
		this, SLOT(receiveUnreadChatMessageSlot(ChatMessage *)));

	ok = ok && QObject::connect(
		chatWidget_, SIGNAL(readChatMessagesSignal(int)),
		this, SLOT(markChatMessagesReadSlot(int)));

	/* DETAILS WIDGET */

	ok = ok && QObject::connect(
		detailsWidget_, SIGNAL(changeShipSectionSignal(SimpleItem &, EShipSectionState)),
		this, SLOT(changeShipSectionSlot(SimpleItem &, EShipSectionState)));

	ok = ok && QObject::connect(
		detailsWidget_, SIGNAL(changeBaseSectionSignal(SimpleItem &, EBaseSectionState)),
		this, SLOT(changeBaseSectionSlot(SimpleItem &, EBaseSectionState)));

	ok = ok && QObject::connect(
		detailsWidget_, SIGNAL(changeSelectedFortressSignal(SimpleItem &)),
		this, SLOT(changeSelectedFortressSlot(SimpleItem &)));

	ok = ok && connect(
		detailsWidget_, SIGNAL(changeSelectedFortressSignal(SimpleItem &)), 
		this, SLOT(changeSelectedFortressSlot(SimpleItem &)));	

	ok = ok && QObject::connect(
		detailsWidget_->ui_.renameButton, SIGNAL(clicked(bool)),
		this, SLOT(renameFortressSlot())
	);

	/* DEVICES */

	ok = ok && connect(
		detailsWidget_->ui_.devicesWidget, SIGNAL(submitDevicesSignal(requestDeviceEnergy &)),
		this, SLOT(submitDevicesSlot(requestDeviceEnergy &)));

	ok = ok && connect(
		detailsWidget_->ui_.devicesWidget, SIGNAL(resetDevicesSignal()),
		this, SLOT(resetDevicesSlot()));

	/* WEAPONS WIDGET */

	ok = ok && connect(
		detailsWidget_->ui_.weaponsWidget, SIGNAL(submitWeaponsSignal(WeaponsChangeDetails &)),
		this, SLOT(submitWeaponsSlot(WeaponsChangeDetails &)));

	ok = ok && connect(
		detailsWidget_->ui_.weaponsWidget, SIGNAL(resetWeaponsSignal()),
		this, SLOT(resetWeaponsSlot()));

	/* NAVIGATION */

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationMoveToSpaceObjectSignal(unsigned long, unsigned long, unsigned long)), 
		this, SLOT(navigationMoveToSpaceObjectSlot(unsigned long, unsigned long, unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationMoveToSignal(unsigned long, position_t, position_t, unsigned long)), 
		this, SLOT(navigationMoveToSlot(unsigned long, position_t, position_t, unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationMoveToSpaceObjectByWarpSignal(unsigned long, unsigned long)), 
		this, SLOT(navigationMoveToSpaceObjectByWarpSlot(unsigned long, unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationPursuitSignal(unsigned long, unsigned long, unsigned long)), 
		this, SLOT(navigationPursuitSlot(unsigned long, unsigned long, unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationBreakWarpSignal(unsigned long)), 
		this, SLOT(navigationBreakWarpSlot(unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationOrbitSignal(unsigned long)), 
		this, SLOT(navigationOrbitSlot(unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationStopSignal(unsigned long)), 
		this, SLOT(navigationStopSlot(unsigned long)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationWarpSignal(unsigned long, position_t, position_t)), 
		this, SLOT(navigationWarpSlot(unsigned long, position_t, position_t)));

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationPlanetsInSystemSignal(id_t)), 
		this, SLOT(navigationPlanetsSlot(id_t)));	

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationDockDownSignal(id_t)), 
		this, SLOT(navigationDockDownSlot(id_t)));	

	ok = ok && connect(
		detailsWidget_->ui_.navigationWidget, SIGNAL(navigationUnboundSignal()), 
		this, SLOT(navigationUnboundSlot()));	

	/* LOGIN */

	ok = ok && connect(
		loginWidget_, SIGNAL(submitLoginSignal(const LoginDetails &)),
		this, SLOT(submitLoginSlot(const LoginDetails &)));

	ok = ok && connect(ui_.loggedWidget, SIGNAL(loginClickedSignal(LoginDetails &)), 
		this, SLOT(loggedWidgetLoginClickedSignal(LoginDetails &)));	

	ok = ok && connect(ui_.loggedWidget, SIGNAL(unloginClickedSignal(LoginDetails &)), 
		this, SLOT(loggedWidgetUnloginClickedSignal(LoginDetails &)));

	ok = ok && QObject::connect(loginWidget_, SIGNAL(submitRegistrationSignal(const RegistrationData &)),
		this, SLOT(submitRegistrationSlot(const RegistrationData &)));

	/* MINING WIDGET */

	ok = ok && connect(detailsWidget_->ui_.miningWidget, SIGNAL(changeQuarkGluonPlasmaQuarryStateSignal(id_t, bool)),
		this, SLOT(changeQuarkGluonPlasmaQuarryStateSlot(id_t, bool)));

	ok = ok && connect(detailsWidget_->ui_.miningWidget, SIGNAL(changeHeavyWaterQuarryStateSignal(id_t, bool)),
		this, SLOT(changeHeavyWaterQuarryStateSlot(id_t, bool)));

	ok = ok && connect(detailsWidget_->ui_.miningWidget, SIGNAL(changeZirconiumCrystalQuarryStateSignal(id_t, bool)),
		this, SLOT(changeZirconiumCrystalQuarryStateSlot(id_t, bool)));

	ok = ok && connect(detailsWidget_->ui_.miningWidget, SIGNAL(changeIlmeniteQuarryStateSignal(id_t, bool)),
		this, SLOT(changeIlmeniteQuarryStateSlot(id_t, bool)));

	/* ANDROIDS WIDGET */

	ok = ok && connect(detailsWidget_->ui_.androidsWidget, SIGNAL(androidsShipResetSignal()),
		this, SLOT(androidsShipResetSlot()));

	ok = ok && connect(detailsWidget_->ui_.androidsWidget, SIGNAL(androidsShipSubmitSignal(ship_androids_request_status &)),
		this, SLOT(androidsShipSubmitSlot(ship_androids_request_status &)));

	ok = ok && connect(detailsWidget_->ui_.androidsWidget, SIGNAL(androidsBaseResetSignal()),
		this, SLOT(androidsBaseResetSlot()));

	ok = ok && connect(detailsWidget_->ui_.androidsWidget, SIGNAL(androidsBaseSubmitSignal(base_androids_request_status &)),
		this, SLOT(androidsBaseSubmitSlot(base_androids_request_status &)));

	/* HANGARS WIDGET */

	ok = ok && connect(detailsWidget_->ui_.hangarWidget, SIGNAL(updateHangarItemSignal(const std::string &)),
		this, SLOT(updateHangarItemSlot(const std::string &)));

	ok = ok && connect(detailsWidget_->ui_.hangarWidget, SIGNAL(updateFortressClassSignal(id_t)),
		this, SLOT(updateFortressClassSlot(id_t)));

	ok = ok && connect(detailsWidget_->ui_.hangarWidget, SIGNAL(updateHangarSignal(id_t, const std::string &)),
		this, SLOT(updateHangarSlot(id_t, const std::string &)));

	ok = ok && connect(detailsWidget_->ui_.hangarWidget, SIGNAL(hangarBuyItemSignal(const HangarServerInputData &)),
		this, SLOT(hangarBuildItemSlot(const HangarServerInputData &)));

	ok = ok && connect(detailsWidget_->ui_.hangarWidget, SIGNAL(hangarBuildShipSignal(id_t, id_t, unsigned long long)),
		this, SLOT(hangarBuildShipSlot(id_t, id_t, unsigned long long)));

	ok = ok && connect(detailsWidget_->ui_.hangarWidget, SIGNAL(hangarCancelItemSignal(id_t, const std::string &)),
		this, SLOT(hangarCancelItemSlot(id_t)));

	/* TRADE */

	ok = ok && connect(tradeWidget_, SIGNAL(inviteTradePartnerSignal(id_t, id_t)),
		this, SLOT(inviteTradePartnerSlot(id_t, id_t)));

	ok = ok && connect(tradeWidget_, SIGNAL(cancelTradeSignal()),
		this, SLOT(cancelTradeSlot()));
	
	ok = ok && connect(tradeWidget_, SIGNAL(tradePartnerFortressesSignal(id_t)),
		this, SLOT(tradePartnerFortressesSlot(id_t)));

	ok = ok && connect(tradeWidget_, SIGNAL(decideTradeInvitationSignal(id_t, id_t, bool)),
		this, SLOT(decideTradeInvitationSlot(id_t, id_t, bool)));	

	ok = ok && connect(tradeWidget_, SIGNAL(startTradeSignal()),
		this, SLOT(startTradeSlot()));	

	ok = ok && connect(tradeWidget_, SIGNAL(moveTradeItemSignal(const trade_client_movement_data &)),
		this, SLOT(moveTradeItemSlot(const trade_client_movement_data &)));	

	ok = ok && connect(tradeWidget_, SIGNAL(commitTradeSignal(id_t, id_t, const client_trade_data &, const client_trade_data &)),
		this, SLOT(commitTradeSlot(id_t, id_t, const client_trade_data &, const client_trade_data & )));

	ok = ok && connect(tradeWidget_, SIGNAL(moveTradeResourceSignal(const trade_resource_movement_data &)),
		this, SLOT(moveTradeResourceSlot(const trade_resource_movement_data &)));

	ok = ok && connect(tradeWidget_, SIGNAL(cancelTradeCommitSignal(id_t, id_t)),
		this, SLOT(cancelTradeCommitSlot(id_t, id_t)));

	ok = ok && connect(tradeWidget_, SIGNAL(ownedFortressesSignal()),
		this, SLOT(ownedFortressesSlot()));

	/* BUILD WIDGET */

	ok = ok && QObject::connect(buildWidget_, SIGNAL(fortressesInConquerRangeSignal(id_t)),
		this, SLOT(fortressesInConquerRangeSlot(id_t)));

	ok = ok && QObject::connect(buildWidget_, SIGNAL(ownedFortressesSignal()),
		this, SLOT(ownedFortressesBuildInformationSlot()));
	
	ok = ok && QObject::connect(buildWidget_, SIGNAL(fortressClassesSignal(id_t)),
		this, SLOT(fortressClassesSlot(id_t)));

	ok = ok && QObject::connect(buildWidget_, SIGNAL(fortressClassDetailsSignal(id_t)),
		this, SLOT(fortressClassDetailsSlot(id_t)));
	
	ok = ok && QObject::connect(buildWidget_, SIGNAL(buildNewBaseShellSignal(id_t, id_t, unsigned long long)),
		this, SLOT(buildNewBaseShellSlot(id_t, id_t, unsigned long long)));

	ok = ok && QObject::connect(buildWidget_, SIGNAL(conquerSignal(id_t, id_t)),
		this, SLOT(conquerSlot(id_t, id_t)));

	ok = ok && QObject::connect(buildWidget_, SIGNAL(tradeSignal(id_t, id_t)),
		this, SLOT(tradeFromBuildSlot(id_t, id_t)));

	/* WAREHOUSES WIDGET */

	ok = ok && connect(detailsWidget_->ui_.warehousesWidget, SIGNAL(mountSignal(id_t, unsigned long long)),
		this, SLOT(mountSlot(id_t, unsigned long long)));

	/* ACCOMMODATIONS WIDGET */

	ok = ok && QObject::connect(detailsWidget_->ui_.accommodationsWidget, SIGNAL(addAccommodationsSignal(unsigned long, accommodation_type)),
		this, SLOT(addAccommodationsSlot(unsigned long, accommodation_type)));

	/* CREW WIDGET */

	ok = ok && QObject::connect(detailsWidget_->ui_.crewWidget, SIGNAL(addCrewSignal(unsigned long, unsigned long, crew_type)),
		this, SLOT(addCrewSlot(unsigned long, unsigned long, crew_type)));

	ok = ok && QObject::connect(detailsWidget_->ui_.crewWidget, SIGNAL(removeCrewSignal(unsigned long, unsigned long, crew_type)),
		this, SLOT(removeCrewSlot(unsigned long, unsigned long, crew_type)));

	assert(ok && "Signals not connected");

	/* DIALOGS */

	connectDialogSignals(tradeWidget_);
	connectDialogSignals(detailsWidget_->ui_.crewWidget);
	connectDialogSignals(detailsWidget_->ui_.accommodationsWidget);	
	connectDialogSignals(detailsWidget_->ui_.shieldsWidget);
	connectDialogSignals(detailsWidget_->ui_.miningWidget);
	connectDialogSignals(detailsWidget_->ui_.otherEquipmentWidget);
	connectDialogSignals(detailsWidget_->ui_.androidsWidget);
	connectDialogSignals(detailsWidget_->ui_.warehousesWidget);
	connectDialogSignals(detailsWidget_->ui_.navigationWidget);

	/* MOUNTING */

	connectUnmountStackableSignals(detailsWidget_->ui_.androidsWidget);	
	connectUnmountStackableSignals(detailsWidget_->ui_.miningWidget);
	connectUnmountStackableSignals(detailsWidget_->ui_.factoriesWidget);
	connectUnmountStackableSignals(detailsWidget_->ui_.weaponsWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.weaponsWidget);
	connectUnmountWeaponsSignals(detailsWidget_->ui_.weaponsWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.shieldsWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.otherEquipmentWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.impulsDriveWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.subspaceDriveWidget);
	connectUnmountWeaponsSignals(detailsWidget_->ui_.hangarWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.cloakingWidget);
	connectUnmountSeparateSignals(detailsWidget_->ui_.sensorsWidget);
}

void MainWindow::connectUnmountWeaponsSignals(QWidget * widget) {
	bool connected = true;

	connected = connected && connect(widget, SIGNAL(unmountSignal(const std::string &, id_t)),
		this, SLOT(unmountSlot(const std::string &, id_t)));

	assert(connected && "Signals not connected");	
}

void MainWindow::connectUnmountSeparateSignals(QWidget * widget) {
	bool connected = true;

	connected = connected && connect(widget, SIGNAL(unmountSignal(const std::string &)),
		this, SLOT(unmountSlot(const std::string &)));

	assert(connected && "Signals not connected");	
}

void MainWindow::connectUnmountStackableSignals(QWidget * widget) {
	bool connected = true;

	connected = connected && connect(widget, SIGNAL(unmountSignal(const std::string &, unsigned long long, unsigned long long)),
		this, SLOT(unmountSlot(const std::string &, unsigned long long, unsigned long long)));

	assert(connected && "Signals not connected");	
}

void MainWindow::connectDialogSignals(QWidget * widget) {
	bool connected = true;
	
	connected = connect(widget, SIGNAL(showDialogSignal()),
		this, SLOT(showDialogSlot()));

	connected = connect(widget, SIGNAL(hideDialogSignal()),
		this, SLOT(hideDialogSlot()));

	assert(connected && "Signals not connected");	
}

void MainWindow::changeSelectedFortressSlot(SimpleItem & item) {
	// When client is in ships or bases but still did not display any of its widget, we tell him to see central information

	if (currentState_.isInState(SHIP_SECTION)) {
		currentState_.shipSectionState.setCurrentShip(item);

		if (currentState_.shipSectionState.isInState(SHIP_NONE)) {
			currentState_.shipSectionState.changeState(SHIP_CENTRAL_INFORMATION);
		}

		updateShipSection();
	}
	else if (currentState_.isInState(BASE_SECTION)) {	
		currentState_.baseSectionState.setCurrentBase(item);

		if (currentState_.baseSectionState.isInState(BASE_NONE)) {
			currentState_.baseSectionState.changeState(BASE_CENTRAL_INFORMATION);
		}

		updateBaseSection();
	}	
}

void MainWindow::clearPlayerState() {
	currentState_.shipSectionState.changeState(SHIP_NONE);
	currentState_.baseSectionState.changeState(BASE_NONE);
	currentState_.changeMainState(MAIN_NONE);
}

void MainWindow::submitLoginSlot(const LoginDetails & loginDetails) {

	if (loginDetails.name == ADMIN_LOGIN) {
		showWarning(L"Přihlášení ke hře", L"Zadal jsi zakázané uživatelské jméno, žádný hráč nemůže mít uživatelské jméno admin", GAME_ICON_INVITATION);
		return;
	}

	LoginDetails lastDetails = ui_.loggedWidget->getLogin();

	if (lastDetails.name != loginDetails.name) {
		clearPlayerState();
	}

	ui_.loggedWidget->setLogin(loginDetails);
	commandClient_->login(loginDetails);
}

MainWindow::~MainWindow()
{
	delete chatWidget_;
	delete treeWidget_;
	delete detailsWidget_;
	delete loginWidget_;
	delete otherviewLogic;

	delete this->mapViewerApp;
	delete this->planetViewerApp;
	delete this->modelViewerApp;
	delete this->sharedData;

	if (unmountDialog_ != NULL) {
		delete unmountDialog_;
	}
}
void MainWindow::initOpenGl(void)
{
	if ( commandClient_ != NULL )
	{
		//WARNING, BUG, HAZARD, RISK, TODO: I am not 100% sure if the context is shared over both widgets correct
		//...but it seems work well

		activatePlanetViewerSlot();  //init openGL Model mode issues
		activateMapViewerSlot(); //init openGL Map mode issues
		activateModelViewerSlot();  //init openGL Model mode issues
		this->renderWidgetSmall->forceInitialize();

		planetViewerActive = false;
		modelViewerActive = false;
		mapViewerActive	= false;
		
		this->hideAllWidgets();
		this->showLoginPanel();
	}
	else
	{
		KODIAK_WARNING<<"commandClient_ == NULL, cannot call void MainWindow::initOpenGl()";
	}
}

void MainWindow::showTrade() {
	setActivity(L"Obchodování");

	hideAllWidgets();
	showTradePanel();
	changeMainState(TRADE);
	
	commandClient_->playerFortresses();
}

void MainWindow::showFight() {
	setActivity(L"Boj");

	hideAllWidgets();
	showFightPanel();
	changeMainState(FIGHT);

	commandClient_->playerFortressesAttackInformation();
}

void MainWindow::showBuild() {
	setActivity(L"Budování");

	hideAllWidgets();
	showBuildPanel();
	changeMainState(BUILD);

	commandClient_->playerFortressesWithBuildInformation();
}

void MainWindow::showChat() {
	setActivity(L"Komunikace");
	changeMainState(CHAT);

	hideAllWidgets();
	showChatPanel();
}


void MainWindow::showShipsTableSlot()
{
	changeMainState(SHIP_SECTION);
	commandClient_->playerShips();

	detailsWidget_->ui_.renameButton->setEnabled(false);
}

void MainWindow::showNavigationSlot()
{
	emit showNavigationSignal();
}

void MainWindow::showBasesTableSlot()
{
	changeMainState(BASE_SECTION);
	// TODO STEPAN Zakomentoval jsem to martinovi, abych necekal 100 let
	// activatePlanetViewerSlot();

	detailsWidget_->ui_.renameButton->setEnabled(false);

	commandClient_->playerBases();
	renderWidgetSmall->setVisible(true);
}

void MainWindow::showScienceTreeSlot()
{
	commandClient_->updateScienceTree();
	emit showScienceTreeSignal();
}

void MainWindow::showChatSlot()
{
	commandClient_->buddies();
}

void MainWindow::showTradeSlot()
{
	showTrade();
}

void MainWindow::showFightSlot()
{
	showFight();
}

void MainWindow::showBuildSlot()
{
	showBuild();
}

void MainWindow::changeMainState(EMainState globalState)
{
	currentState_.changeMainState(globalState);
}

void MainWindow::showShipsTable(GameItemsVector & items)
{
	setActivity(L"Detaily lodě");
	hideAllWidgets();

	detailsWidget_->showShipsTable(items);

	if (currentState_.shipSectionState.hasCurrentShip()) {
		detailsWidget_->changeSelectedFortress(currentState_.shipSectionState.getCurrentShip());
	}

	showDetailsWidget();	
}

void MainWindow::showBasesTable(GameItemsVector & items)
{
	setActivity(L"Detaily základny");
	hideAllWidgets();
	
	detailsWidget_->showBasesTable(items);

	if (currentState_.baseSectionState.hasCurrentBase()) {
		detailsWidget_->changeSelectedFortress(currentState_.baseSectionState.getCurrentBase());
	}

	showDetailsWidget();	
}

bool MainWindow::isInMainState(EMainState state) {
	return currentState_.isInState(state);
}

void MainWindow::showSpaceMapSlot(void)
{
	changeMainState(SPACE_MAP);
	setActivity(L"Hvězdná mapa");

	this->hideAllWidgets();
	this->activateMapViewerSlot();

}
void MainWindow::showSpaceMap( void)
{
	setActivity(L"Hvezdna mapa");
	changeMainState(SPACE_MAP);	

	hideAllWidgets();
	
	this->renderWidgetBig->setVisible( true );
	this->otherviewWidget->setVisible( true );
}
void MainWindow::updateSpaceMap(GameItemsVector & items)
{
	otherviewLogic->clearShips();
			
	if ( items.empty() )
	{
		return;
	}

	for ( int i=0; i< items.size(); ++i)
	{
		ShipType shipType = (ShipType) (items[i].classId-1); //because server is indexing types from 1, but we use enums from 0

		otherviewLogic->insertShip(  items[i].id, items[i].name, shipType   );

		if ( items[i].id == this->activeShipIdSpaceMap )
		{
			otherviewLogic->selectedShipSlot( i, false );
		}
	}

}

void MainWindow::showScienceTree()
{
	setActivity(L"Strom vědy");
	changeMainState(TREE);

	hideAllWidgets();
	showScienceTreePanel();
}

QString MainWindow::createDetailsTitle(int id, const std::wstring & name)
{
	return QString::fromUtf16((name.c_str())) + QString::fromUtf16(L", ID ") + QString::number(id);
}

void MainWindow::hideDetailsWidget()
{
	detailsWidget_->setVisible(false);
}

void MainWindow::showDetailsWidget()
{
	detailsWidget_->setVisible(true);
}

void MainWindow::hideScienceTreePanel()
{
	treeWidget_->setVisible(false);
}

void MainWindow::showScienceTreePanel()
{
	treeWidget_->setVisible(true);
}

ScienceTreeWidget * MainWindow::createAndInitTree(QWidget * parentWidget)
{
	// Create node widget with main windows as a parrent
	ScienceTreeWidget * treeWidget = new ScienceTreeWidget(parentWidget);	

	// Set tokens multiplicators
	double multiplicators[] = {0.3, 0.55, 0.3};
	treeWidget->setTokenMultiplicators(multiplicators, 3);
	
	// Set showing options
	treeWidget->setShowPoints(ALL);
	treeWidget->setShowTokens(LEAF);

	bool ok = connect(treeWidget, SIGNAL(changeScienceTreeStateSignal(sciencetree_raw_data &)),
		this, SLOT(changeScienceTreeStateSlot(sciencetree_raw_data &)));

	ok = ok && connect(treeWidget, SIGNAL(updateScienceTreeStateSignal()),
		this, SLOT(updateScienceTreeStateSlot()));

	assert(ok && "Signals not connected");

	void changeScienceTreeStateSignal(sciencetree_raw_data & state);

	return treeWidget;
}

void MainWindow::updateScienceTreeStateSlot() {
	showScienceTreeSlot();
}

void MainWindow::changeScienceTreeStateSlot(sciencetree_raw_data & state) {
	commandClient_->changeScienceTree(state);
}

void MainWindow::hideAllWidgets()
{
	hideChatPanel();
	hideScienceTreePanel();
	hideDetailsWidget();
	hideTradePanel();
	hideSmallRenderPanel();
	hideBigRenderPanel();
	hideAttackPanel();
	hideLoginPanel();
	hideFightPanel();
	hideBuildPanel();
}

void MainWindow::answerUpdateDeviceEnergyState(id_t fortressId, answerDeviceEnergy & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update to not selected section")) {
		return;
	}

	detailsWidget_->ui_.devicesWidget->setState(state);
}

void MainWindow::answerUpdateWeaponsInformation(id_t fortressId, weapons_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(SHIP_SECTION) || currentState_.isInState(BASE_SECTION)) {
		if (!assertFortressEquality(fortressId, "Received update to not selected section")) {
			return;
		}

		detailsWidget_->ui_.weaponsWidget->setState(state);
	}
	else if (currentState_.isInState(FIGHT)) {
		fightWidget_->updateWeaponsInformation(fortressId, state);
	}
}

void MainWindow::setActivity(const std::wstring & activity) {
	// Do nothing
}

void MainWindow::showLoginPanel()
{
	hideAllWidgets();

	setActivity(L"Logování");
	loginWidget_->setVisible(true);
	loginWidget_->setEnabled(true);	
	
	ui_.mainMenuPanel->setVisible(false);

	loginWidget_->setGeometry(5, 5, loginWidget_->width(), loginWidget_->height());
}

void MainWindow::hideLoginPanel()
{
	this->ui_.mainMenuPanel->setVisible( true );

	loginWidget_->setVisible(false);	
}

void MainWindow::showChatPanel()
{
	chatWidget_->setVisible(true);
	chatWidget_->showChat();
}

void MainWindow::hideChatPanel()
{
	chatWidget_->setVisible(false);
	chatWidget_->hideChat();
}

void MainWindow::showBigRenderPanel()
{
	setActivity(L"Render");

	hideAllWidgets();
	renderWidgetBig->setVisible(true);
	otherviewWidget->setVisible( true );
}

void MainWindow::hideBigRenderPanel()
{
	renderWidgetBig->setVisible(false);
	otherviewWidget ->setVisible( false );
}


void MainWindow::showSmallRenderPanel( SimpleItem & item )
{
	setActivity(L"Render");

	if ( this->modelViewerActive )
	{
		// -1 because server is not indexing from 0 like client data types
		this->synchronizer_->spaceshipSynchronize( (ShipType) (item.classId-1) );
	}

	if ( this->planetViewerActive )
	{
		string planetType;

		switch ( item.classId % PLANET_TYPE_COUNT )
		{
		case 0:
			planetType = PLANET_TYPE_0;
			break;

		case 1:
			planetType = PLANET_TYPE_1;
			break;

		case 2:
			planetType = PLANET_TYPE_2;
			break;

		case 3:
			planetType = PLANET_TYPE_3;
			break;

		case 4:
			planetType = PLANET_TYPE_4;
			break;

		case 5:
			planetType = PLANET_TYPE_5;
			break;

		case 6:
			planetType = PLANET_TYPE_6;
			break;

		default:
			planetType = PLANET_TYPE_0;
			KODIAK_WARNING<<"MainWindow::showSmallRenderPanel : unkown planet type, used PLANET_TYPE_0";
		}

		BaselineData planetData;
		GraphicMapper::getInstance()->generateBaselineData( item.id, planetType, planetData );

		//activate openGL context ( renderWidgetSmall share context with renderWidgetBig!!!)
		this->renderWidgetBig->makeCurrent();

		this->synchronizer_->baselineSynchronize( planetData);
	}
	
	renderWidgetSmall->setVisible( true );
	detailsWidget_->showRender();
}

void MainWindow::hideSmallRenderPanel()
{
	renderWidgetSmall->setVisible( false );
}

void MainWindow::hideAttackPanel()
{
	this->attackWidget->setVisible( false );
}


void MainWindow::addChatBuddy(ChatBuddy * buddy) {
	chatWidget_->addBuddy(buddy);
}

void MainWindow::receiveChatMessage(ChatMessage * message) {
	chatWidget_->receiveMessage(message);
}

void MainWindow::sendChatMessageSlot(ChatMessage * message) {
	commandClient_->sendChatMessage(message);
}

void MainWindow::receiveUnreadChatMessageSlot(ChatMessage * message) {
	incomingWidget_->addUnreadChatMessage(message);
}

void MainWindow::markChatMessagesReadSlot(int count) {
	incomingWidget_->removeUnreadMessages(count);
}

void MainWindow::showTradePanel()
{
	tradeWidget_->setVisible(true);
}

void MainWindow::hideTradePanel()
{
	tradeWidget_->setVisible(false);
}

void MainWindow::showFightPanel()
{
	fightWidget_->setVisible(true);
}

void MainWindow::hideFightPanel()
{
	fightWidget_->setVisible(false);
}

void MainWindow::showBuildPanel()
{
	buildWidget_->setVisible(true);
}

void MainWindow::hideBuildPanel()
{
	buildWidget_->setVisible(false);
}

void MainWindow::showDevices() {
	setActivity(L"Energetický okruh");

	detailsWidget_->ui_.devicesWidget->show();

	detailsWidget_->ui_.devicesWidget->setCurrentEnergyAccumulator(25);
	detailsWidget_->ui_.devicesWidget->setMaximumEnergyAccumulator(40);

	detailsWidget_->ui_.devicesWidget->setCurrentEnergySupply(25);
	detailsWidget_->ui_.devicesWidget->setMaximumEnergySupply(40);

	detailsWidget_->ui_.devicesWidget->resize(680, 680);
	detailsWidget_->ui_.devicesWidget->initWidget();

	commandClient_->updateDeviceEnergyState(1);
}

void MainWindow::answerBases(GameItemsVector & items) {
	showBasesTable(items);
	updateBaseSection();
}

void MainWindow::answerShips(GameItemsVector & items) {
	setWaitingForUpdateFortressResponse(false);

	switch (currentState_.mainState)
	{
		case SPACE_MAP:
		{
			if ( this->renderWidgetBig->isVisible() && this->otherviewWidget->isVisible() )
			{
				//widget is visible, just update data
				updateSpaceMap( items );
			}
			else
			{
				//widget is not visible, show & update data
				showSpaceMap();
				updateSpaceMap( items );
			}

			break;
		}
		case SHIP_SECTION:
			if (!currentState_.shipSectionState.isWaiting) {
				showShipsTable(items);
				updateShipSection();
			}
			else {
				currentState_.shipSectionState.isWaiting = false;

				showShipsTable(items);

				SimpleItem * item = detailsWidget_->findFortressById(activeShipIdSpaceMap);

				if (item == NULL) {
					KODIAK_WARNING << "MainWindow::answerShips(GameItemsVector & items) MAIN_SHIP_PREPARED state, shipId not found in GameItemsVector -> ignored";
					return;
				}
			
				currentState_.shipSectionState.setCurrentShip(*item);
				detailsWidget_->changeSelectedFortress(*item);				
				updateShipSection();
			}

			break;

		case TRADE:
			tradeWidget_->setOwnedFortresses(items);
			break;

		break;

		default:
			KODIAK_WARNING<<"MainWindow::answerShips(GameItemsVector & items) method called, but unsupported state -> ignored";
			break;
	}
}

void MainWindow::answerFortressesAttackInformation(const std::vector<fortress_attack_information>& fortresses) {
	setWaitingForUpdateFortressResponse(false);
	fightWidget_->setOwnedFortresses(fortresses);
}


void MainWindow::answerShipLocation( id_t shipId, location_status & activeShipLocation )
{
	setWaitingForUpdateFortressResponse(false);

	if ( shipId == this->activeShipIdSpaceMap )
	{
		//information is valid for our active ship
		this->activeShipLocation = activeShipLocation;
	}
	else
	{
		//information is not valid for our active ship
		this->activeShipLocation.actualSpaceObject = 0;
		this->activeShipLocation.actualStar = 0;
		this->activeShipLocation.nearestStar = 0;
	}

	//something like callback method call
	if (this->callPlanetsInStarAreaWithUpdatedNearestStar == true )
	{
		this->commandClient_->planetsInStarArea( activeShipLocation.nearestStar  );
		this->callPlanetsInStarAreaWithUpdatedNearestStar = false;
	}

}

void MainWindow::answerPlayerExploredStars( discovered_stars & discoveredStars )
{
	setWaitingForUpdateFortressResponse(false);

	for ( int i=0; i< discoveredStars.dsc_stars.size(); ++i )
	{
		StarData starData;
		starData.id = discoveredStars.dsc_stars[i].id;
		starData.position.set_data( discoveredStars.dsc_stars[i].pos.x , 0, discoveredStars.dsc_stars[i].pos.y );
		this->synchronizer_->starSynchronize(starData );	
	}
		
}

void MainWindow::answerNavigationPlanets(NavigationPlanetsInStarAreaDetails & planetsInArea) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(planetsInArea.shipId, "Received update to not selected section")) {
		return;
	}

	if (currentState_.isInState(SHIP_SECTION, SHIP_NAVIGATION)) {
		detailsWidget_->ui_.navigationWidget->setPlanets(planetsInArea);
	}
}

void MainWindow::answerPlanetsInStarArea(PlanetsInStarAreaDetails & planetsInStarArea) 
{
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(SPACE_MAP)) 
	{
		PlanetDetails star;
		star.id = planetsInStarArea.areaId; //areaId == starId according Jakub Melka
		star.name = planetsInStarArea.sunName;
		star.pivotX = planetsInStarArea.planets[0].pivotX;	//TODO FIXME star position not konwn!!!
		star.pivotY = planetsInStarArea.planets[0].pivotY;	//TODO FIXME star position not konwn!!!
		star.size = planetsInStarArea.sunObjectRadius; 
		star.type = planetsInStarArea.sunType;
		star.weight = planetsInStarArea.sunWeight;
		star.type = starPlanet;
		//GameConstants::MICRO_COORD_CONVERTOR.setClientCoordCenter( Point_3<double>( star.pivotX, 0, star.pivotY) );

		synchronizeGenericPlanet( star, planetsInStarArea.gameTime ); // sunType ignored...only 0 type at this moment
		
		for (std::vector<PlanetDetails>::iterator it = planetsInStarArea.planets.begin(); it != planetsInStarArea.planets.end(); ++it) 
		{
			synchronizeGenericPlanet(*it, planetsInStarArea.gameTime );
		}
	}
}

void MainWindow::submitDevicesSlot(requestDeviceEnergy & state) {
	if (!currentState_.hasCurrentFortress()) {
		return;
	}

	commandClient_->changeDeviceEnergyState(currentState_.getCurrentFortress().id, state);
}

void MainWindow::resetDevicesSlot() {
	if (!currentState_.hasCurrentFortress()) {
		return;
	}

	commandClient_->updateDeviceEnergyState(currentState_.getCurrentFortress().id);
}

void MainWindow::navigationMoveToSpaceObjectSlot(unsigned long shipId, unsigned long spaceObjectId, unsigned long limit) {
	commandClient_->navigationMoveToSpaceObject(shipId, spaceObjectId, limit);
	commandClient_->navigationStatus(shipId);
	commandClient_->shipJourneyDetails(shipId);
}

void MainWindow::navigationMoveToSlot(unsigned long shipId, position_t positionx, position_t positiony, unsigned long limit) {
	commandClient_->navigationMoveTo(shipId, positionx, positiony, limit);

	this->activeShipIdSpaceMap = shipId;
}

void MainWindow::navigationMoveToSpaceObjectByWarpSlot(unsigned long shipId, unsigned long spaceObjectId) {
	commandClient_->navigationMoveToSpaceObjectByWarp(shipId, spaceObjectId);
	commandClient_->navigationStatus(shipId);
	commandClient_->shipJourneyDetails(shipId);
}

void MainWindow::navigationPursuitSlot(unsigned long shipId, unsigned long spaceObjectId, unsigned long limit) { 
	commandClient_->navigationPursuit(shipId, spaceObjectId, limit);
}

void MainWindow::navigationBreakWarpSlot(unsigned long shipId) {
	commandClient_->navigationBreakWarp(shipId);
}

void MainWindow::navigationOrbitSlot(unsigned long shipId) {
	commandClient_->navigationOrbit(shipId);
}

void MainWindow::navigationStopSlot(unsigned long shipId) {
	commandClient_->navigationStop(shipId);
}

void MainWindow::navigationWarpSlot(unsigned long shipId, position_t positionx, position_t positiony) {
	commandClient_->navigationWarp(shipId, positionx, positiony);
}

void MainWindow::navigationPlanetsSlot(id_t starId) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::navigationPlanetsSlot(id_t starId)")) {
		return;
	}

	commandClient_->navigationPlanetsInStarArea(currentState_.getCurrentFortress().id, starId);
}

void MainWindow::navigationDockDownSlot(id_t baseId) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::navigationDockDownSignal(id_t baseId)")) {
		return;
	}

	commandClient_->navigationDockDown(currentState_.getCurrentFortress().id, baseId);
}

void MainWindow::navigationUnboundSlot() {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::navigationUnboundSignal()")) {
		return;
	}

	commandClient_->navigationUnbound(currentState_.getCurrentFortress().id);
}

void MainWindow::answerShipJourneyDetails(ShipJourneyDetailsFAIL & details) {
	setWaitingForUpdateFortressResponse(false);

	detailsWidget_->ui_.navigationWidget->setShipJourneyDetails(details);
	
	showWarning(L"Aktualizace navigačního stavu lodě", L"Aktualizace navigačního stavu lodě se nezdařila", GAME_ICON_IMPULS_DRIVE, details.reason);
}

void MainWindow::answerShipJourneyDetails(ShipJourneyDetailsSTANDARD & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(details.shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.navigationWidget->setShipJourneyDetails(details);
}

void MainWindow::answerShipJourneyDetails(ShipJourneyDetailsPURSUIT & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(details.shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.navigationWidget->setShipJourneyDetails(details);
}

void MainWindow::answerShipJourneyDetails(ShipJourneyDetailsMOVE_TO & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(details.shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.navigationWidget->setShipJourneyDetails(details);
}

void MainWindow::answerShipJourneyDetails(ShipJourneyDetailsMOVE_TO_SPACE_OBJECT & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(details.shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.navigationWidget->setShipJourneyDetails(details);
}

void MainWindow::answerChangeDeviceEnergyStateERROR(unsigned long shipId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);

	detailsWidget_->ui_.devicesWidget->setStateERROR(shipId, reason);
	showWarning(L"Změna rozdělení energie", L"Změna rozdělení energie se nepodařila, nastala chyba", GAME_ICON_DEVICE_DITRIBUTION, reason); 
}

void MainWindow::answerUpdateDeviceEnergyStateFAIL(unsigned long shipId, const std::string & reason) {	
	setWaitingForUpdateFortressResponse(false);

	showWarning(L"Aktualizace rozdělení energie", L"Aktualizace rozdělení energie se nepodařila, nastala chyba", GAME_ICON_DEVICE_DITRIBUTION, reason); 
}

void MainWindow::answerBuddies(std::vector<ChatBuddy *> buddies) {
	chatWidget_->setBuddies(buddies);
	showChat();
}

void MainWindow::setAttackTargetSlot( unsigned long targetShipId )
{
	this->attackFortressSlot( this->activeShipIdSpaceMap, targetShipId );
}

void MainWindow::getAttackListSlot( unsigned long shipId )
{
	this->attackWidget->clearRecords();
	this->attackWidget->setVisible( true );

	this->fortressInWeaponsRangeSlot( shipId );
}

void MainWindow::setSelectedShipSlot( unsigned long shipId )
{
	this->activeShipIdSpaceMap = shipId;

	//hide attack panel, selected ship changed, attack widget must be updated first
	this->attackWidget->setVisible( false );
}

void MainWindow::getRadarDataSlot( unsigned long shipId )
{
	if (  shipId == 0 ) return;

	//send request to server
	commandClient_->updateRadarData( shipId );

}

void MainWindow::answerUpdateNavigationStatus(NavigationStatus & navigationStatus) {
	setWaitingForUpdateFortressResponse(false);

	detailsWidget_->ui_.navigationWidget->setNavigationState(navigationStatus);
}

void MainWindow::answerShipsInShipAreaFAIL(id_t areaId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
}

void MainWindow::answerPlanetsInStarAreaFAIL(id_t areaId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
}

void MainWindow::answerNavigationShipFAIL(id_t shipId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);

	updateNavigation(shipId);
	showWarning(L"Navigace lodi", L"Navigace lodi selhala", GAME_ICON_IMPULS_DRIVE, fail);
}

void MainWindow::updateNavigation(id_t shipId) {
	if (!currentState_.shipSectionState.isInState(SHIP_NAVIGATION)) {
		return;
	}

	if (shipId != currentState_.getCurrentFortress().id) {
		return;
	}

	if (!detailsWidget_->ui_.navigationWidget->isInWarp()) {
		commandClient_->navigationStatus(shipId);
	}

	commandClient_->shipJourneyDetails(shipId);
}

void MainWindow::answerNavigationMoveToSpaceObject(id_t shipId) {
	setWaitingForUpdateFortressResponse(false);

	updateNavigation(shipId);
	detailsWidget_->ui_.navigationWidget->answerNavigationMoveToSpaceObject();
}

void MainWindow::answerNavigationMoveToSpaceObjectByWarp(id_t shipId) {
	setWaitingForUpdateFortressResponse(false);

	updateNavigation(shipId);
	detailsWidget_->ui_.navigationWidget->answerNavigationMoveToSpaceObjectByWarp();
}

void MainWindow::answerNavigationMoveTo(id_t shipId) {
	setWaitingForUpdateFortressResponse(false);

	updateNavigation(shipId);
	detailsWidget_->ui_.navigationWidget->answerNavigationMoveTo();
}

void MainWindow::answerNavigationPursuit(id_t shipId) {
	setWaitingForUpdateFortressResponse(false);

	updateNavigation(shipId);
	detailsWidget_->ui_.navigationWidget->answerNavigationPursuit();
}

void MainWindow::answerNavigationBreakWarp(id_t shipId) {
	updateNavigation(shipId);

	detailsWidget_->ui_.navigationWidget->answerNavigationBreakWarp();
}

void MainWindow::answerNavigationOrbit(id_t shipId) {
	updateNavigation(shipId);

	detailsWidget_->ui_.navigationWidget->answerNavigationOrbit();
}

void MainWindow::answerNavigationStop(id_t shipId) {
	updateNavigation(shipId);

	detailsWidget_->ui_.navigationWidget->answerNavigationStop();
}

void MainWindow::answerNavigationWarp(id_t shipId) {
	updateNavigation(shipId);

	detailsWidget_->ui_.navigationWidget->answerNavigationWarp();
}

void MainWindow::answerNavigationDockDown(id_t shipId, id_t baseId, DockingResult result) {
	updateNavigation(shipId);

	detailsWidget_->ui_.navigationWidget->answerNavigationDockDown(shipId, baseId, result);

	if (result == DR_OK) {
		showMessage(L"Přistání lodí na základnu", L"Přistání lodí na základnu proběhlo úspěšně", GAME_ICON_BASE);
	}
	else {
		showWarning(L"Přistání lodí na základnu", L"Přistání lodí na základnu se nezdařilo", GAME_ICON_BASE, NavigationWidget::dockingResult2WString(result));
	}
}

void MainWindow::answerNavigationUnbound(id_t shipId, DockingResult result) {
	updateNavigation(shipId);

	if (result == DR_OK) {
		showMessage(L"Vzlétnutí lodě ze základny", L"Vzlétnutí lodě ze základny proběhlo úspěšně", GAME_ICON_BASE);
	}
	else {
		showWarning(L"Vzlétnutí lodě ze základny", L"Vzlétnutí lodě ze základny se nezdařilo", GAME_ICON_BASE, NavigationWidget::dockingResult2WString(result));
	}
}

void MainWindow::answerNavigationMoveToSpaceObjectFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationMoveToSpaceObjectFAIL();

	showWarning(L"Navigace lodě impulsním pohonem", L"Navigace lodě k hvězdnému objektu impulsním pohonem se nezdařila", GAME_ICON_IMPULS_DRIVE);
}

void MainWindow::answerNavigationMoveToSpaceObjectByWarpFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationMoveToSpaceObjectByWarpFAIL();

	showWarning(L"Navigace lodě podprostorovým pohonem", L"Navigace lodě k hvězdnému objektu podprostorovým pohonem se nezdařila", GAME_ICON_SUBSPACE_DRIVE);
}

void MainWindow::answerNavigationMoveToFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationMoveToFAIL();

	showWarning(L"Navigace lodě impulsním pohonem", L"Navigace lodě na vlastní souřadnice impulsním pohonem pohonem se nezdařila", GAME_ICON_IMPULS_DRIVE);
}

void MainWindow::answerNavigationPursuitFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationPursuitFAIL();

	showWarning(L"Pronásledování lodě", L"Pronásledování lodě se nezdařilo", GAME_ICON_IMPULS_DRIVE);
}

void MainWindow::answerNavigationBreakWarpFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationBreakWarpFAIL();

	showWarning(L"Zastavení podprostorového pohonu", L"Zastavení podprostorového pohonu", GAME_ICON_SUBSPACE_DRIVE);
}

void MainWindow::answerNavigationOrbitFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationOrbitFAIL();

	showWarning(L"Obíhání planety", L"Zahájení obíhání planety se nezdařilo", GAME_ICON_IMPULS_DRIVE);
}

void MainWindow::answerNavigationStopFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationStopFAIL();

	showWarning(L"Zastavení impulsního pohonu", L"Zastavení impulsního pohonu se nezdařilo", GAME_ICON_IMPULS_DRIVE);
}

void MainWindow::answerNavigationWarpFAIL() {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	detailsWidget_->ui_.navigationWidget->answerNavigationWarpFAIL();

	showWarning(L"Navigace lodě podprostorovým pohonem", L"Navigace lodě podprostorovým pohonem se nezdařila", GAME_ICON_SUBSPACE_DRIVE);
}

void MainWindow::answerNavigationDockDownFAIL(id_t shipId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	showWarning(L"Přistání lodí na základnu", L"Přistání lodí na základnu se nezdařilo", GAME_ICON_BASE, reason);
}

void MainWindow::answerNavigationUnboundFAIL(id_t shipId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.hasCurrentFortress()) {
		updateNavigation(currentState_.getCurrentFortress().id);
	}

	showWarning(L"Vzlétnutí lodi ze základny", L"Vzlétnutí lodi ze základny se nezdařilo", GAME_ICON_BASE, reason);
}

void MainWindow::answerUpdateScienceTree(ScienceTreeRawUpdateData & data) {
	setWaitingForUpdateFortressResponse(false);

	treeWidget_->setState(data);
	showScienceTree();
}

void MainWindow::answerUpdateCentralInformation(CentralInfoDetails & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(details.shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.centralInfoWidget->setState(details);
}

void MainWindow::answerUpdateShieldsInformation(ShieldsDetails & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(details.shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.shieldsWidget->setState(details);
}

void MainWindow::answerUpdateImpulsDriveInformation(id_t shipId, impulse_drive_status & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.impulsDriveWidget->setState(details);
}

void MainWindow::answerUpdateSubspaceDriveInformation(id_t shipId, subspace_drive_status & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.subspaceDriveWidget->setState(details);
}

void MainWindow::answerUpdateMainframeInformation(id_t shipId, mainframe_status & details) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(shipId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.mainframeWidget->setState(details);
}

void MainWindow::activateMapViewerSlot(void)
{
	renderWidgetSmall->setApp( NULL );
	renderWidgetBig->setApp( mapViewerApp );

	if ( ! renderWidgetBig->isInitialized() )
	{
		renderWidgetBig->initializeGL();
	}

	//set keyboard focus to he widget
	this->renderWidgetBig->setFocus();

	modelViewerActive = false;
	mapViewerActive	= true;
	planetViewerActive= false;

	this->updateSpaceMap();
}

void MainWindow::activateModelViewerSlot(void)
{
	renderWidgetBig->setApp( NULL );
	renderWidgetSmall->setApp( modelViewerApp );
	renderWidgetSmall->initializeGL();
		
	//set keyboard focus to he widget
	this->renderWidgetSmall->setFocus();

	modelViewerActive = true;
	mapViewerActive	= false;
	planetViewerActive= false;
}
void MainWindow::activatePlanetViewerSlot(void)
{
	renderWidgetBig->setApp( NULL );
	renderWidgetSmall->setApp( planetViewerApp );
	renderWidgetSmall->initializeGL();

	//set keyboard focus to he widget
	this->renderWidgetSmall->setFocus();

	modelViewerActive = false;
	mapViewerActive	= false;
	planetViewerActive= true;
}
void MainWindow::renderSlot(void)
{
	if ( mapViewerActive )
	{
		bool centerCamera = false;

		if ( this->newShipSelected && this->mapViewerApp!= NULL )
		{
			this->mapViewerApp->setActiveShipId( this->activeShipIdSpaceMap );
			this->mapViewerApp->signalizeShip( this->activeShipIdSpaceMap);
			//this->mapViewerApp->centerCameraToShip( this->activeShipIdSpaceMap );
			centerCamera = true;
			this->newShipSelected = false;
			this->centerAsSoonAsPossible = true;
		}

		SpaceShip *activeShipPtr =  this->mapViewerApp->getGalaxyPart()->findShip(  this->activeShipIdSpaceMap  );
		if ( activeShipPtr== NULL /*|| activeShipPtr->inWarp || activeShipPtr->inBase*/ )
		{
			// do no center camera to them!!!
			
			centerCamera = false;
		}

		//if all conditions are ok, then center camera
		if ( centerCamera )
		{
			this->mapViewerApp->centerCameraToShip( this->activeShipIdSpaceMap );
		}

		if ( this->centerAsSoonAsPossible && this->isPossibleToCenter && activeShipPtr!= NULL /*&& !activeShipPtr->inWarp && !activeShipPtr->inBase*/ )
		{
			this->mapViewerApp->signalizeShip( this->activeShipIdSpaceMap);
			this->mapViewerApp->centerCameraToShip( this->activeShipIdSpaceMap );
			this->centerAsSoonAsPossible = false;
			this->isPossibleToCenter = false;
		}

		renderWidgetBig->updateGL();

		//################################
		//update otherview selected ship data
		unsigned long activeShipId = 0;
		bool shipFound = this->otherviewLogic->getShipId( this->otherviewLogic->getActiveIdx(), activeShipId );
		SpaceShip *activeShip = this->mapViewerApp->getGalaxyPart()->findShip( activeShipId );
		if ( activeShip != NULL )
		{
			this->otherviewLogic->refreshShipState( activeShip->type, activeShip->lifePercentage, activeShip->shieldPercentage, QString( activeShip->name.c_str() ) );
		}
		//################################

		return;
	}
	
	if ( planetViewerActive || modelViewerActive )
	{
		renderWidgetSmall->updateGL();

		return;
	}
}
void MainWindow::simulateSlot( float dt )
{
	if ( modelViewerActive )
	{
		modelViewerApp->simulate( dt );

		//if openGl widget has no focus & no mouse button is pressed then set focus to the OpenGL widget
		if ( !this->renderWidgetSmall->hasFocus() && QApplication::mouseButtons().testFlag( Qt::NoButton ) )
		{
			this->renderWidgetSmall->setFocus();
		}
	}

	if ( mapViewerActive )
	{
		mapViewerApp->simulate( dt );

		//if openGl widget has no focus & no mouse button is pressed then set focus to the OpenGL widget
		if ( !this->renderWidgetBig->hasFocus() && QApplication::mouseButtons().testFlag( Qt::NoButton ) )
		{
			this->renderWidgetBig->setFocus();
		}
	}

	if ( planetViewerActive )
	{
		planetViewerApp->simulate( dt );

		//if openGl widget has no focus & no mouse button is pressed then set focus to the OpenGL widget
		if ( !this->renderWidgetSmall->hasFocus() && QApplication::mouseButtons().testFlag( Qt::NoButton ) )
		{
			this->renderWidgetSmall->setFocus();
		}
	}
}

void MainWindow::loggedWidgetLoginClickedSignal(LoginDetails & loginDetails) {
	ui_.loggedWidget->setLogin(loginDetails);	
	commandClient_->login(loginDetails);
}

void MainWindow::loggedWidgetUnloginClickedSignal(LoginDetails & loginDetails) {
	commandClient_->disconnectFromServer();
	ui_.loggedWidget->setStatus(false);
	hideAllWidgets();
	showLoginPanel();
}

void MainWindow::shipSettingsSlot(unsigned long shipId ) {
	changeMainState(SHIP_SECTION);
	currentState_.shipSectionState.isWaiting = true;
	commandClient_->playerShips();
}

void MainWindow::shipNavigationSlot(unsigned long shipId) {
	changeMainState(SHIP_SECTION);
	currentState_.shipSectionState.changeState(SHIP_NAVIGATION);
	currentState_.shipSectionState.isWaiting = true;
	commandClient_->playerShips();
}

void MainWindow::shipWeaponsSlot(unsigned long shipId) {
	changeMainState(SHIP_SECTION);
	currentState_.shipSectionState.changeState(SHIP_WEAPONS);
	currentState_.shipSectionState.isWaiting = true;
	commandClient_->playerShips();
}

void MainWindow::shipsInShipAreaDone(void)
{
	//this method is called from CommandClient when shipsInArea update was done ( and ships data were uppdated )

	//REMOVE NOT UPDATER SHIPS IN DB
	//NOTE: for spaceMap only
	this->mapViewerApp->removeSpaceMapObjectsOlderThan( EPSILON, true, false);

	//do not remove ships from long range sensors ships...they are deleted automatic if not actualized
	//this->mainWindow_->mapViewerApp->removeRadarObjectsOlderThan(0.1, true, false);

	 //data actualized, now we can center camera to active ship ( which was now updated )
	this->isPossibleToCenter  = true;

}
void MainWindow::updateSpaceMap( void )
{
	/*
	this->commandClient_->getPlayerDiscoveredStars();
	this->commandClient_->planetsInStarArea( this->activeShipLocation.nearestStar  );
	this->commandClient_->shipsInShipArea( this->activeShipIdSpaceMap  );
	this->commandClient_->shipLocationInfo( this->activeShipIdSpaceMap );
	this->commandClient_->playerShips();
	*/

	//pokus o jine a lepsi usporadani prikazu

	//KODIAK_DEBUG<<"updateSpaceMap request send!!!";
	this->commandClient_->getPlayerDiscoveredStars();
	this->commandClient_->playerShips();
	this->callPlanetsInStarAreaWithUpdatedNearestStar = true;

	if ( this->activeShipIdSpaceMap == false ) return;

	this->commandClient_->shipLocationInfo( this->activeShipIdSpaceMap );
	this->commandClient_->shipsInShipArea( this->activeShipIdSpaceMap  );
	
	//TODO, PRIORITY, FIXME...this is not working correct, returns that ship is in warp also in cases where it isnt!!!
	this->commandClient_->getShipWarpInfo( this->activeShipIdSpaceMap );
}

void MainWindow::submitWeaponsSlot(WeaponsChangeDetails & state) {
	if (!currentState_.hasCurrentFortress()) {
		return;
	}

	commandClient_->changeFortressWeaponsState(currentState_.getCurrentFortress().id, state);	
}

void MainWindow::resetWeaponsSlot() {
	if (!currentState_.hasCurrentFortress()) {
		return;
	}

	commandClient_->updateFortressWeaponsInformation(currentState_.getCurrentFortress().id);	
}

void MainWindow::fortressesInConquerRangeSlot(id_t fortressId) {
	commandClient_->fortressesInConquerRange(fortressId);	
}

void MainWindow::fortressClassesSlot(id_t fortressId) {
	commandClient_->availableFortressClasses(fortressId);	
}

void MainWindow::ownedFortressesBuildInformationSlot() {
	commandClient_->playerFortressesWithBuildInformation();
}

void MainWindow::submitWeaponsSlot(id_t fortressId, WeaponsChangeDetails & state) {
	commandClient_->changeFortressWeaponsState(fortressId, state);	
}

void MainWindow::resetWeaponsSlot(id_t fortressId) {
	commandClient_->updateFortressWeaponsInformation(fortressId);	
}

void MainWindow::answerUpdateWeaponsInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace zbraní", L"Změna zbraní se nezdařila, nastala chyba", GAME_ICON_WEAPONS, fail); 
}

void MainWindow::answerChangeWeaponsInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Změna nastavení zbraní", L"Změna nastavení zbraní se nezdařila, nastala chyba", GAME_ICON_WEAPONS, fail); 
}

void MainWindow::answerUpdateSubspaceDriveInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace podprostorového pohonu", L"Aktualizace podprostorového pohonu se nezdařila, nastala chyba", GAME_ICON_SUBSPACE_DRIVE, fail); 
}

void MainWindow::answerUpdateImpulsDriveInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace impulsního pohonu", L"Aktualizace impulsního pohonu se nezdařila, nastala chyba", GAME_ICON_IMPULS_DRIVE, fail); 
}

void MainWindow::answerUpdateMainframeInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace hlavního počítače", L"Aktualizace hlavního počítače se nezdařila, nastala chyba", GAME_ICON_MAINFRAME, fail); 
}

void MainWindow::answerUpdateShieldsInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace štítů", L"Aktualizace štítů se nezdařila, nastala chyba", GAME_ICON_SHIELDS, fail); 
}

void MainWindow::answerUpdateCentralInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace centrálních informací", L"Aktualizace centrálních informací se nezdařila, nastala chyba", GAME_ICON_CENTRAL_INFORMATION, fail); 
}

void MainWindow::answerUpdateBaseHangarsInformationFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace hangárů", L"Aktualizace hangárů nezdařila, nastala chyba", GAME_ICON_HANGARS, reason); 
}

void MainWindow::answerShipWarpInfo( WarpInfo &shipWarpInfo )
{
	setWaitingForUpdateFortressResponse(false);

	ShipWarpInfo warpInfo;
	warpInfo.id = shipWarpInfo.shipId;
	warpInfo.dstPosition.set_data( shipWarpInfo.dstPosX, 0,  shipWarpInfo.dstPosY );
	warpInfo.srcPosition.set_data( shipWarpInfo.sposX, 0,  shipWarpInfo.sposY );
	warpInfo.position.set_data( shipWarpInfo.posX, 0,  shipWarpInfo.posY );
	warpInfo.stateChange = shipWarpInfo.stateChange;
	warpInfo.inWarp = shipWarpInfo.inWarp;
	warpInfo.speed = shipWarpInfo.speed;
	warpInfo.name = shipWarpInfo.shipName;
	warpInfo.type = (ShipType) (shipWarpInfo.shipType);
	this->synchronizer_->warpSynchronize( warpInfo );
}

void MainWindow::synchronizeGenericPlanet(PlanetDetails & details, const dv_time::datetime &gameTime ) 
{
	GenericPlanetData planetData;
   
	planetData.id = details.id;
	const Vector_3<double> axisY( 0, 1, 0 );
	planetData.axis = axisY;	//rotate always around axisY
	planetData.pivot.set_data(details.pivotX, 0, details.pivotY);
	planetData.name = details.name;
	planetData.radius = details.radius;
	planetData.speed = details.speed; 
	planetData.angle = details.angle;
	planetData.objectSize = details.size;

	for ( int i=0; i< details.enemyTargetIds.size(); ++i)
	{
		MissileTarget missileTarget;
		missileTarget.enemyTargetId = details.enemyTargetIds[i].first;

		if (  details.enemyTargetIds[i].first == false)
		{
			missileTarget.targetType = NO_TARGET;
		}
		else if ( details.enemyTargetIds[i].second )
		{
			missileTarget.targetType = SHIP_TARGET;
		}
		else
		{
			missileTarget.targetType = PLANET_TARGET;
		}

		planetData.enemyTargetData.push_back( missileTarget );
	}

	//color is always white
	const CTriCol WHITE( 1.0, 1.0, 1.0 );
	planetData.color = WHITE;

	string planetType;


	if ( details.type == 99 )
	{
		planetType = STAR_TYPE;
		planetData.coronaTextureName = "starCorona";
	}
	else
	{
		switch ( details.type % PLANET_TYPE_COUNT )
		{
			case 0:
				planetType = PLANET_TYPE_0;
				planetData.coronaTextureName = "corona";
				break;

			case 1:
				planetType = PLANET_TYPE_1;
				planetData.coronaTextureName = "corona";
				break;

			case 2:
				planetType = PLANET_TYPE_2;
				planetData.coronaTextureName = "corona";
				break;

			case 3:
				planetType = PLANET_TYPE_3;
				planetData.coronaTextureName = "corona";
				break;

			case 4:
				planetType = PLANET_TYPE_4;
				planetData.coronaTextureName = "corona";
				break;

			case 5:
				planetType = PLANET_TYPE_5;
				planetData.coronaTextureName = "corona";
				break;

			case 6:
				planetType = PLANET_TYPE_6;
				planetData.coronaTextureName = "corona";
				break;

			default:
				planetType = PLANET_TYPE_0;
				planetData.coronaTextureName = "corona";

				KODIAK_WARNING<<"MainWindow::synchronizeGenericPlanet : unkown planet type, used PLANET_TYPE_0";
		}
		}

	string textureName;
	GraphicMapper::getInstance()->generateOuterSurfaceTexure( planetData.id, planetType, textureName );
	planetData.textureName = textureName;
	this->synchronizer_->planetSynchronize(planetData);		
}

void MainWindow::answerUpdateCrewInformation(id_t fortressId, crew_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.crewWidget->setState(state);
}

void MainWindow::answerUpdateCrewInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);

	showWarning(L"Aktualizace posádky", L"Aktualizace posádky se nepodařila, nastala chyba", GAME_ICON_CREW, fail); 
}

bool MainWindow::checkIfWaitingForUpdateFortressResponse() {
	if (isWaitingForUpdateFortressResponse) {
		return true;
	}
	else {
		return false;
	}
}

void MainWindow::setWaitingForUpdateFortressResponse(bool wait) {
	isWaitingForUpdateFortressResponse = wait;

	if (isWaitingForUpdateFortressResponse == false) {
		// If there is no waiting notification, we are done
		if (!isThereAnotherUpdateFortressNotification) {
			return;
		}

		// If there is waiting notification, we update current fortress if any and note that there is no longer
		// any waiting notification

		isThereAnotherUpdateFortressNotification = false;

		id_t fortressToUpdateID = 0;

		switch (currentState_.mainState) {
		case SPACE_MAP:
			fortressToUpdateID = this->activeShipIdSpaceMap;
			break;
		case SHIP_SECTION:	
			fortressToUpdateID = this->currentState_.getCurrentFortress().id;
			break;

		case BASE_SECTION:	
			fortressToUpdateID = this->currentState_.getCurrentFortress().id;
			break;

		case FIGHT:
			fortressToUpdateID = this->fightWidget_->getSelfFortressId();
			break;
		}

		if (fortressToUpdateID != 0) {
			KODIAK_DEBUG_COUT << 
				"Using waiting notification to update fortress " + KODIAK_ENDL;

			answerUpdateFortress(fortressToUpdateID);
		}
	}
}

void MainWindow::answerUpdateFortress(id_t fortressId ) 
{
	if (checkIfWaitingForUpdateFortressResponse()) {
		if (isThereAnotherUpdateFortressNotification) {
		/*	KODIAK_DEBUG_COUT << 
				"Received update fortress notification when waiting for response to previous one. "
				"Another notification already noted. So this one is ignored." + KODIAK_ENDL;*/
		}
		else {	
			/*KODIAK_DEBUG_COUT << 
				"Received update fortress notification when waiting for response to previous one. "
				"There is no other waiting notification. So this one is noted as waiting notification." + KODIAK_ENDL;*/

			isThereAnotherUpdateFortressNotification = true;		
		}

		return;
	}

	switch (currentState_.mainState) {

	case SPACE_MAP:
		//update data only if server send us active ship id, other update request ignored
		if  ( this->activeShipIdSpaceMap == fortressId )
		{
			setWaitingForUpdateFortressResponse(true);
			this->updateSpaceMap();		
		}
		break;


	case SHIP_SECTION:	
		if (!currentState_.shipSectionState.hasCurrentShip()) {
			return;
		}

		if (currentState_.shipSectionState.getCurrentShipId() != fortressId) {
			return;
		}

		// Do not update in navigation, it is not neccessary
		if (currentState_.isInState(SHIP_SECTION, SHIP_NAVIGATION)) {
			return;
		}

		setWaitingForUpdateFortressResponse(true);
		updateShipSection();		
		break;

	case BASE_SECTION:	
		if (currentState_.baseSectionState.hasCurrentBase()) {
			if (currentState_.baseSectionState.getCurrentBaseId() == fortressId) 
			{
				setWaitingForUpdateFortressResponse(true);
				updateBaseSection();				
			}
		}
		break;

	case FIGHT:
		if (fightWidget_->getSelfFortressId() != 0) {
			setWaitingForUpdateFortressResponse(true);
			commandClient_->updateFortressWeaponsInformation(fightWidget_->getSelfFortressId());
		}
		break;
	}
}

void MainWindow::answerUpdateShip(id_t shipId)  {
	if (currentState_.isInState(SHIP_SECTION, SHIP_NAVIGATION)) {
		updateNavigation(shipId);
	}
}

void MainWindow::answerUpdateQuarryInformation(id_t fortressId, quarry_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.miningWidget->setState(fortressId, state);
}

void MainWindow::answerUpdateQuarryInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace těžebních informací", L"Aktualizace těžebních informací selhala", GAME_ICON_QUARRYING, fail);
}

void MainWindow::answerChangeQuarryStateFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Změna stavu těžebních informací", L"Změna stavu těžebních informací selhala", GAME_ICON_QUARRYING, fail);
}

void MainWindow::changeQuarkGluonPlasmaQuarryStateSlot(id_t fortressId, bool isQuarrying) {
	commandClient_->changeQuarkGluonPlasmaQuarryState(fortressId, isQuarrying);
}

void MainWindow::changeHeavyWaterQuarryStateSlot(id_t fortressId, bool isQuarrying) {
	commandClient_->changeHeavyWaterQuarryState(fortressId, isQuarrying);
}

void MainWindow::changeZirconiumCrystalQuarryStateSlot(id_t fortressId, bool isQuarrying) {
	commandClient_->changeZirconiumCrystalQuarryState(fortressId, isQuarrying);
}

void MainWindow::changeIlmeniteQuarryStateSlot(id_t fortressId, bool isQuarrying) {
	commandClient_->changeIlmeniteQuarryState(fortressId, isQuarrying);
}

void MainWindow::answerUpdateAccommodationsInformation(id_t fortressId, accommodation_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.accommodationsWidget->setState(state);
}

void MainWindow::answerUpdateAccommodationsInformationFAIL(id_t fortressId, const std::string & fail) {
	showWarning(L"Aktualizace ubikací", L"Aktualizace ubikací se nepodařila, nastala chyba", GAME_ICON_ACCOMMODATIONS, fail); 
}

void MainWindow::answerUpdateOtherEquipmentInformation(id_t fortressId, other_equipment_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.otherEquipmentWidget->setState(state);
}

void MainWindow::answerUpdateOtherEquipmentInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace ostatního vybavení", L"Aktualizace ostatního vybavení se nepodařila, nastala chyba", GAME_ICON_EQUIPMENT, fail); 
}

void MainWindow::answerUpdateFactoriesInformation(id_t fortressId, factories_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.factoriesWidget->setState(state);
}

void MainWindow::answerUpdateFactoriesInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace továren", L"Aktualizace továren se nepodařila, nastala chyba", GAME_ICON_FACTORIES, fail); 
}

void MainWindow::answerUpdateWarehousesInformation(id_t fortressId, warehouses_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.warehousesWidget->setState(state);
}

void MainWindow::answerUpdateWarehousesInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace skladů", L"Aktualizace skladů se nepodařila, nastala chyba", GAME_ICON_WAREHOUSES, fail); 
}

void MainWindow::answerUpdateShipAndroidsInformation(id_t fortressId, ship_androids_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.androidsWidget->setState(state);
}

void MainWindow::answerUpdateShipAndroidsInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace androidů", L"Aktualizace androidů se nepodařila, nastala chyba", GAME_ICON_ANDROIDS, fail); 
}

void MainWindow::answerUpdateBaseAndroidsInformation(id_t fortressId, base_androids_status & state) {
	setWaitingForUpdateFortressResponse(false);

	if (!assertFortressEquality(fortressId, "Received update from server for not selected fortress")) {
		return;
	}

	detailsWidget_->ui_.androidsWidget->setState(state);
}

void MainWindow::answerUpdateBaseAndroidsInformationFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace androidů", L"Aktualizace androidů se nepodařila, nastala chyba", GAME_ICON_ANDROIDS, fail); 
}

void MainWindow::androidsShipResetSlot() {
	if (!assertFortressExistence(
		"Not active fortress when reseting androids state in method "
		"void MainWindow::androidsResetSlot()")) {
		return;
	}

	commandClient_->updateShipAndroidsInformation(currentState_.getCurrentFortress().id);
}

void MainWindow::androidsBaseResetSlot() {
	if (!assertFortressExistence(
		"Not active fortress when reseting androids state in method "
		"void MainWindow::androidsResetSlot()")) {
		return;
	}

	commandClient_->updateBaseAndroidsInformation(currentState_.getCurrentFortress().id);
}

void MainWindow::androidsShipSubmitSlot(ship_androids_request_status & state) {
	if (!assertFortressExistence(
		"Not active fortress when submiting androids state in method "
		"void MainWindow::androidsSubmitSlot(androids_assignment &)")) {
		return;
	}

	commandClient_->changeShipAndroidsState(currentState_.getCurrentFortress().id, state);
}

void MainWindow::androidsBaseSubmitSlot(base_androids_request_status & state) {
	if (!assertFortressExistence(
		"Not active fortress when submiting androids state in method "
		"void MainWindow::androidsSubmitSlot(androids_assignment &)")) {
		return;
	}

	commandClient_->changeBaseAndroidsState(currentState_.getCurrentFortress().id, state);
}

bool MainWindow::assertFortressExistence(const std::string & errorText) {
	if (isInMainState(SHIP_SECTION)) {
		if (currentState_.shipSectionState.hasCurrentShip()) {
			return true;
		}
	}
	else if (isInMainState(BASE_SECTION)) {
		if (currentState_.baseSectionState.hasCurrentBase()) {
			return true;
		}
	}

	KODIAK_WARNING << errorText;
	return false;
}

bool MainWindow::assertFortressEquality(id_t fortressId, const std::string & errorText) {
	if (!currentState_.hasCurrentFortress()) {
		KODIAK_WARNING << errorText;
		return false;
	}

	if (!(currentState_.getCurrentFortress().id == fortressId)) {
		KODIAK_WARNING << errorText;
		return false;
	}

	return true;
}

void MainWindow::answerChangeShipAndroidsStateFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Změna nastavení androidů", L"Změna nastavení androidů se nepodařila, nastala chyba", GAME_ICON_ANDROIDS, fail); 
}

void MainWindow::answerChangeBaseAndroidsStateFAIL(id_t fortressId, const std::string & fail) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Změna nastavení androidů", L"Změna nastavení androidů se nepodařila, nastala chyba", GAME_ICON_ANDROIDS, fail); 
}

void MainWindow::loadConnections(const QString & filePath) {
	QString applicationPath = QCoreApplication::applicationDirPath();
	QString updatedFilePath = applicationPath + "/" + filePath;

	loginWidget_->loadConnections(updatedFilePath);
}

void MainWindow::connectionLostEvent(int milliseconds) {
	ui_.loggedWidget->setStatus(false);
	ui_.loggedWidget->setLogin(commandClient_->getCurrentLogin());
	commandClient_->reconnect();
	
	KODIAK_WARNING << "You have been disconnected due to long inactivity. This is probably because of pause during debugging. You were automatically reconnected";
}

void MainWindow::answerUpdateBaseHangarItemInformation(hangar_item_status & state) {
	setWaitingForUpdateFortressResponse(false);
	detailsWidget_->ui_.hangarWidget->dataSynchronize(state);
}

void MainWindow::answerUpdateBaseHangarsInformation(hangars_status & state) {
	setWaitingForUpdateFortressResponse(false);
	detailsWidget_->ui_.hangarWidget->dataSynchronize(state);
}

void MainWindow::updateHangarItemSlot(const std::string & patternName) {
 	commandClient_->updateBaseHangarItemInformation(patternName);
}

void MainWindow::updateFortressClassSlot(id_t hangarId) {
	commandClient_->fortressClassData(hangarId);
}

void MainWindow::updateHangarSlot(id_t hangarId, const std::string & patternName) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::updateHangarSignal(id_t hangarId)")) {
		return;
	}

	commandClient_->updateBaseHangarsInformation(currentState_.getCurrentFortress().id, hangarId, patternName);
}

void MainWindow::hangarBuildItemSlot(const HangarServerInputData & data) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::hangarBuildItemSlot(const HangarServerInputData & data)")) {
		return;
	}

	commandClient_->hangarBuildItem(currentState_.getCurrentFortress().id, data);
}

void MainWindow::hangarBuildShipSlot(id_t hangarId, id_t fortressClassId, unsigned long long buildingTitanium) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::hangarBuildShipSlot(id_t hangarId, id_t fortressClassId, unsigned long long buildingTitanium))")) {
		return;
	}

	commandClient_->hangarBuildShip(currentState_.getCurrentFortress().id, hangarId, fortressClassId, buildingTitanium);
}

void MainWindow::hangarCancelItemSlot(id_t hangarId) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::hangarCancelItemSlot(id_t hangarId)")) {
		return;
	}

	commandClient_->hangarCancelItem(currentState_.getCurrentFortress().id, hangarId);
}

void MainWindow::notifyUpdate() {
	if (currentState_.isInState(SHIP_SECTION) || currentState_.isInState(BASE_SECTION)) {
		detailsWidget_->notifyUpdate();
	}
	else if (currentState_.isInState(FIGHT)) {	
		fightWidget_->notifyUpdate();
	}
}

void MainWindow::showDialogSlot() {
	ui_.shadowFrame->setVisible(true);
}

void MainWindow::hideDialogSlot() {
	ui_.shadowFrame->setVisible(false);
}

void MainWindow::unmountFortressDevice(const std::string & patternName, unsigned long long working, unsigned long long damaged) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::unmountSlot(const std::string & patternName, unsigned long long working, unsigned long long damaged)")) {
		return;
	}

	unmount_device_info data;

	data.fortressId = currentState_.getCurrentFortress().id;
	data.concreteId = 0;
	data.patternName = patternName;
	data.working = working;
	data.damaged = damaged;

	commandClient_->unmountFortressDevice(data);
}

void MainWindow::unmountFortressDevice(const std::string & patternName) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::unmountSlot(const std::string & patternName, unsigned long long working, unsigned long long damaged)")) {
		return;
	}

	unmount_device_info data;

	data.fortressId = currentState_.getCurrentFortress().id;
	data.concreteId = 0;
	data.patternName = patternName;
	data.working = 0;
	data.damaged = 0;	

	commandClient_->unmountFortressDevice(data);
}

void MainWindow::unmountFortressDevice(const std::string & patternName, id_t itemId) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::unmountSlot(const std::string & patternName, unsigned long long working, unsigned long long damaged)")) {
		return;
	}

	unmount_device_info data;

	data.fortressId = currentState_.getCurrentFortress().id;
	data.concreteId = itemId;
	data.patternName = patternName;
	data.working = 0;
	data.damaged = 0;

	commandClient_->unmountFortressDevice(data);
}

void MainWindow::answerSendTradeInvitation(const trade_invitation_data & invitation, const trade_data & selfTradeData, const std::string & reason, const std::string & tradeRole) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(BUILD)) {
		showTradePanel();
	}

	tradeWidget_->answerSendTradeInvitation(invitation, selfTradeData, reason, tradeRole);
}

void MainWindow::answerSendTradeInvitation(const trade_invitation_data & invitation, const trade_data & selfTradeData, const trade_data & partnerTradeData, const std::string & reason, const std::string & tradeRole) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(BUILD)) {
		hideAllWidgets();
		showTradePanel();
		tradeWidget_->answerSendTradeInvitationFromBuild(invitation, selfTradeData, partnerTradeData, reason, tradeRole);
	}
	else {
		tradeWidget_->answerSendTradeInvitation(invitation, selfTradeData, partnerTradeData, reason, tradeRole);
	}
}

void MainWindow::answerSendTradeInvitation(const trade_invitation_data & invitation, const std::string & reason, const std::string & tradeRole) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerSendTradeInvitation(invitation, reason, tradeRole);
}

void MainWindow::receiveTradeInvitationDecision(const trade_invitation_data & invitation) {
	tradeWidget_->receiveTradeInvitationDecision(invitation);
}

void MainWindow::receiveTradeInvitationDecision(const trade_invitation_data & invitation, const trade_data & tradeData) {
	tradeWidget_->receiveTradeInvitationDecision(invitation, tradeData);
}

void MainWindow::answerDecideTradeInvitation(const trade_invitation_data & invitation) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerDecideTradeInvitation(invitation);
}

void MainWindow::answerDecideTradeInvitation(const trade_invitation_data & invitation, const trade_data & tradeData) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerDecideTradeInvitation(invitation, tradeData);
}

void MainWindow::inviteTradePartnerSlot(id_t ownedFortressId, id_t partnerFortressId) {
	commandClient_->sendTradeInvitation(ownedFortressId, partnerFortressId);
}

void MainWindow::cancelTradeSlot() {
	commandClient_->cancelTrade();
}

void MainWindow::tradePartnerFortressesSlot(id_t ownedFortressId) {
	commandClient_->tradePartnerFortresses(ownedFortressId);
}

void MainWindow::answerTradePartnerFortressesFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace pevností k obchodování", L"Aktualizace pevností k obchodování se nezdařila", GAME_ICON_TRADE, reason);
}

void MainWindow::answerUncontrollableFortressesFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace pevností k ovládnutí", L"Aktualizace pevností k ovládnutí se nezdařila", GAME_ICON_TRADE, reason);
}

void MainWindow::answerTradePartnerFortresses(id_t fortressId, const std::vector<SimpleItem> & ownedFortresses, const std::vector<SimpleItem> & notOwnedFortresses) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->setSecondOwnedFortresses(ownedFortresses);
	tradeWidget_->setEnemyFortresses(notOwnedFortresses);
}

void MainWindow::answerUncontrollableFortresses(id_t fortressId, const std::vector<FortressInRangeData> & ships, const std::vector<FortressInRangeData> & bases) {
	setWaitingForUpdateFortressResponse(false);
	buildWidget_->setUncontrolledFortresses(fortressId, ships, bases);
}

void MainWindow::receiveTradeInvitation(const trade_invitation_data & invitation) {
	tradeWidget_->receiveTradeInvitation(invitation);
}

void MainWindow::decideTradeInvitationSlot(id_t hostFortressId, id_t invitedFortressId, bool accept) {
	commandClient_->decideTradeInvitation(hostFortressId, invitedFortressId, accept);
}

void MainWindow::startTradeSlot() {
	showTrade();
}

void MainWindow::answerCancelTrade(id_t ownedFortressId, id_t partnerFortressId, const std::string & reason, const std::string & tradeRole) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerCancelTrade(ownedFortressId, partnerFortressId, reason, tradeRole);
}

void MainWindow::receiveTradeCancelation(id_t ownedFortressId, id_t partnerFortressId) {
	tradeWidget_->receiveTradeCancelation(ownedFortressId, partnerFortressId);
}

void MainWindow::answerMoveTradeItem(const trade_movement_data & tradeData, bool isAuthor) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerMoveTradeItem(tradeData, isAuthor);
}

void MainWindow::answerMoveTradeItemFAIL(const trade_movement_data & tradeData, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Přesunutí předmětu při obchodování", L"Přesunutí předmětu při obchodování selhalo", GAME_ICON_TRADE, reason);
}

void MainWindow::moveTradeItemSlot(const trade_client_movement_data & tradeData) {
	commandClient_->moveTradeItem(tradeData);
}

void MainWindow::answerCommitTrade(id_t selfFortressId, id_t partnerFortressId, ETradingResult result) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->commitTrade(selfFortressId, partnerFortressId, result);
}

void MainWindow::answerPrepareCommitTrade(id_t selfFortressId, id_t partnerFortressId, ETradingCommitRole commitRole) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->prepareCommitTrade(selfFortressId, partnerFortressId, commitRole);
}

void MainWindow::commitTradeSlot(id_t selfFortressId, id_t partnerFortressId, const client_trade_data & selfOffer, const client_trade_data & partnerOffer) {
	commandClient_->commitTrade(selfFortressId, partnerFortressId, selfOffer, partnerOffer);
}

void MainWindow::moveTradeResourceSlot(const trade_resource_movement_data & data) {
	setWaitingForUpdateFortressResponse(false);
	commandClient_->moveTradeResource(data);
}

void MainWindow::answerMoveTradeResource(const trade_resource_movement_data & tradeData, bool isAuthor) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerMoveTradeResource(tradeData, isAuthor);
}

void MainWindow::answerMoveTradeResourceFAIL(const trade_resource_movement_data & tradeData, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Přesunutí suroviny při obchodování", L"Přesunutí suroviny při obchodování selhalo", GAME_ICON_TRADE, reason);
}

void MainWindow::answerUnmountFortressDeviceFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Odmontování zařízení", L"Odmontování zařízení se nezdařilo", GAME_ICON_EQUIPMENT, reason);
}

void MainWindow::answerMountFortressDeviceFAIL(id_t fortressId, id_t itemId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Namontování zařízení", L"Namontování zařízení se nezdařilo", GAME_ICON_EQUIPMENT, reason);
}

void MainWindow::cancelTradeCommitSlot(id_t selfFortressId, id_t partnerFortressId) {
	commandClient_->cancelTradeCommit(selfFortressId, partnerFortressId);
}

void MainWindow::answerCancelTradeCommit(id_t selfFortressId, id_t partnerFortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->answerCancelTradeCommit(selfFortressId, partnerFortressId, reason);
}

void MainWindow::answerUnmountFortressDevice(const unmount_device_info & unmountData,  const std::string & mountingResult) {
	setWaitingForUpdateFortressResponse(false);

	showDialogSlot();
	if (mountingResult == PROTOCOL_MOUNTING_RESULT_DONE) {
		if (unmountData.working > 0 || unmountData.damaged > 0) {
			showMessage(QString::fromUtf16(L"Odmontování zařízení"), QString::fromUtf16(L"Odmontování zařízení proběhlo úspěšně. Bylo odmontováno celkem ")
				+ Settings::instance().formatNumber(unmountData.working) + QString::fromUtf16(L" nepoškozených a ")
				+ Settings::instance().formatNumber(unmountData.damaged) + QString::fromUtf16(L" poškozených zařízení"), GAME_ICON_EQUIPMENT);
		}
		else {
			showMessage(QString::fromUtf16(L"Odmontování zařízení"), QString::fromUtf16(L"Odmontování zařízení proběhlo úspěšně. "), GAME_ICON_EQUIPMENT);
		}

		if (currentState_.isInState(SHIP_SECTION)) {
			updateShipSection();
		}
		else if (currentState_.isInState(BASE_SECTION)) {
			updateBaseSection();
		}
	}
	else {
		showWarning(L"Odmontování zařízení", L"Odmontování zařízení se nezdařilo", GAME_ICON_EQUIPMENT, mountingResult);
	}
}

void MainWindow::cancelUnmountDialogSlot() {
	unmountDialog_->reject();
	hideDialogSlot();
}

void MainWindow::submitUnmountDialogSlot() {
	if (!unmountDialog_->isCanceled()) {
		if (unmountDialog_->getUnmountType() == UNMOUNT_TYPE_SEPARATE) {
			std::string patternName = unmountDialog_->getPatternName();
			unmountFortressDevice(patternName);
		}
		else if (unmountDialog_->getUnmountType() == UNMOUNT_TYPE_STACKABLE) {
			std::string patternName = unmountDialog_->getPatternName();
			unsigned long long working = unmountDialog_->getWorking();
			unsigned long long damaged = unmountDialog_->getDamaged();
			unmountFortressDevice(patternName, working, damaged);
		}
		else if (unmountDialog_->getUnmountType() == UNMOUNT_TYPE_CONCRETE) {			
			std::string patternName = unmountDialog_->getPatternName();
			id_t itemId = unmountDialog_->getItemId();
			unmountFortressDevice(patternName, itemId);
		}
	}

	unmountDialog_->accept();
	hideDialogSlot();
}

void MainWindow::createUnmountDialog() {
	unmountDialog_ = new UnmountDialog(this);
																						   
	bool ok = connect(unmountDialog_, SIGNAL(submitSignal()), this, SLOT(submitUnmountDialogSlot()));
	ok = ok && connect(unmountDialog_, SIGNAL(cancelSignal()), this, SLOT(cancelUnmountDialogSlot()));
	ok = ok && connect(unmountDialog_, SIGNAL(rejected()), this, SLOT(rejectDialogSlot()));
	assert(ok && "Signals not connected");

	unmountDialog_->setWindowFlags(Qt::SplashScreen);
}

void MainWindow::unmountSlot(const std::string & patternName, unsigned long long working, unsigned long long damaged) {
	showDialogSlot();

	if (unmountDialog_ == NULL) {
		createUnmountDialog();
	}	

	unmountDialog_->setDialog(patternName, working, damaged);	
	 
	unmountDialog_->show();
	unmountDialog_->raise();
	unmountDialog_->activateWindow();
}

void MainWindow::unmountSlot(const std::string & patternName, id_t itemId) {
	showDialogSlot();

	if (unmountDialog_ == NULL) {
		createUnmountDialog();
	}	

	unmountDialog_->setDialog(patternName, itemId);	
	 
	unmountDialog_->show();
	unmountDialog_->raise();
	unmountDialog_->activateWindow();
}

void MainWindow::unmountSlot(const std::string & patternName) {	
	showDialogSlot();

	if (unmountDialog_ == NULL) {
		createUnmountDialog();	
	}

	unmountDialog_->setDialog(patternName);	

	unmountDialog_->show();
	unmountDialog_->raise();
	unmountDialog_->activateWindow();
}

void MainWindow::answerMountFortressDevice(id_t fortressId, id_t itemId, const std::string & mountingResult) {
	setWaitingForUpdateFortressResponse(false);

	if (mountingResult == PROTOCOL_MOUNTING_RESULT_DONE) {
		//mountDialog_->setAsDoneSuccess(patternName, mountingResult);
	}
	else {
		//mountDialog_->setAsDoneFail(patternName, mountingResult);
	}
}

void MainWindow::mountSlot(id_t itemId, unsigned long long count) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::mountSlot(id_t, unsigned long long)")) {
		return;
	}

	mount_device_info data;

	data.count = count;	
	data.fortressId = currentState_.getCurrentFortress().id;
	data.itemId = itemId;

	commandClient_->mountFortressDevice(data);
}

void MainWindow::answerFortressesInRange(const fortress_attack_information & ownedFortress, const std::vector<SimpleItem> & ships, const std::vector<SimpleItem> & bases) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(FIGHT)) {
		fightWidget_->setEnemyFortresses(ownedFortress, ships, bases);
	}

	//----------------------
	if ( currentState_.isInState( SPACE_MAP ) )
	{
		this->attackWidget->clearRecords();
		vector<AttackRecord> records;

		for ( int i=0; i< ships.size(); ++i)
		{
			AttackRecord record;
			record.playerName = ships[i].realmName.c_str();
			record.id = ships[i].id;
			record.fortressName = ships[i].name.c_str();

			records.push_back( record );
		}

		for ( int i=0; i< bases.size(); ++i)
		{
			AttackRecord record;
			record.playerName = bases[i].realmName.c_str();
			record.id = bases[i].id;
			record.fortressName = bases[i].name.c_str();

			records.push_back( record );
		}

		this->attackWidget->insertRecord( records );
	}
}

void MainWindow::fortressInWeaponsRangeSlot(id_t fortressId) {
	commandClient_->fortressInWeaponsRange(fortressId);
}

void MainWindow::fortressWeaponsSettingsSlot(id_t fortressId) {
	commandClient_->updateFortressWeaponsInformation(fortressId);
}

void MainWindow::attackFortressSlot(id_t selfFortressId, id_t enemyFortressId) {
	commandClient_->attackFortress(selfFortressId, enemyFortressId);
}

void MainWindow::stopAttackFortressSlot(id_t selfFortressId) {
	commandClient_->stopAttackFortress(selfFortressId);
}

void MainWindow::answerAttackFortress(id_t selfFortressId, id_t enemyFortressId) {
	setWaitingForUpdateFortressResponse(false);
	fightWidget_->attackStartAcknowledgement(selfFortressId, enemyFortressId);
}

void MainWindow::answerAvailableFortressClassesFAIL(id_t selfFortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace dostupných tříd pevností", L"Aktualizace dostupných tříd pevností se nezdařila", GAME_ICON_FACTORIES, reason);
}

void MainWindow::answerFortressClassDataFAIL(id_t fortressClassId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace třídy pevnost", L"Aktualizace třídy pevnosti se nezdařila", GAME_ICON_FACTORIES, reason);
}

void MainWindow::answerConquerFortressFAIL(id_t selfFortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Ovládnutí nekontrolované pevnosti", L"Ovládnutí nekontrolované pevnosti se nezdařilo", GAME_ICON_WEAPONS, reason);
}

void MainWindow::answerBuildNewBaseShellFAIL(id_t selfFortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Postavení nové základny", L"Postavení nové základny se nezdažilo", GAME_ICON_BASE, reason);
}

void MainWindow::answerAttackFortressFAIL(id_t selfFortressId, id_t enemyFortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Zahájení útoku", L"Zahájení útoku selhalo", GAME_ICON_WEAPONS, reason);
}

void MainWindow::answerStopAttackFortress(id_t selfFortressId) {
	setWaitingForUpdateFortressResponse(false);
	fightWidget_->attackStopAcknowledgement(selfFortressId);
}

void MainWindow::answerStopAttackFortressFAIL(id_t selfFortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Zastavení útoku", L"Zastavení útoku selhalo", GAME_ICON_WEAPONS, reason);
}

void MainWindow::submitWarningDialogSlot() {
	warningDialog_->accept();
	hideDialogSlot();
}

void MainWindow::createWarningDialog() {
	warningDialog_ = new WarningDialog(this);
																						   
	bool connected = connect(warningDialog_, SIGNAL(submitSignal()), this, SLOT(submitWarningDialogSlot()));
	connected = connected && connect(warningDialog_, SIGNAL(rejected()), this, SLOT(rejectDialogSlot()));
	assert(connected && "Signals not connected");

	warningDialog_->setWindowFlags(Qt::SplashScreen);
}

void MainWindow::showWarning(const std::wstring & title, const std::wstring & message, const std::string & iconKey, const std::wstring & reason) {
	if (messageDialog_ == NULL) {
		createMessageDialog();
	}

	showDialogSlot();

	messageDialog_->setTitle(title);
	messageDialog_->setMessage(message);
	messageDialog_->setReason(reason);
	messageDialog_->setIcon(iconKey);
	messageDialog_->setSuccess(false);

	messageDialog_->show();
	messageDialog_->raise();
	messageDialog_->activateWindow();
}

void MainWindow::showWarning(const std::wstring & title, const std::wstring & message, const std::string & iconKey, const std::string & reason) {
	if (messageDialog_ == NULL) {
		createMessageDialog();
	}

	showDialogSlot();

	messageDialog_->setTitle(title);
	messageDialog_->setMessage(message);
	messageDialog_->setReasonByKey(reason);
	messageDialog_->setIcon(iconKey);
	messageDialog_->setSuccess(false);

	messageDialog_->show();
	messageDialog_->raise();
	messageDialog_->activateWindow();
}

void MainWindow::submitMessageDialogSlot() {
	messageDialog_->accept();
	hideDialogSlot();
}

void MainWindow::createMessageDialog() {
	messageDialog_ = new MessageDialog(this);
																						   
	bool connected = connect(messageDialog_, SIGNAL(submitSignal()), this, SLOT(submitMessageDialogSlot()));
	connected = connected && connect(messageDialog_, SIGNAL(rejected()), this, SLOT(rejectDialogSlot()));
	assert(connected && "Signals not connected");

	messageDialog_->setWindowFlags(Qt::SplashScreen);
}

void MainWindow::showMessage(const std::wstring & title, const std::wstring & message, const std::string & iconKey) {
	if (messageDialog_ == NULL) {
		createMessageDialog();
	}

	showDialogSlot();

	messageDialog_->setTitle(title);
	messageDialog_->setMessage(message);
	messageDialog_->setIcon(iconKey);
	messageDialog_->setSuccess(true);
	messageDialog_->setReason(L"");

	messageDialog_->show();
	messageDialog_->raise();
	messageDialog_->activateWindow();
}

void MainWindow::showMessage(const QString & title, const QString & message, const std::string & iconKey) {
	if (messageDialog_ == NULL) {
		createMessageDialog();
	}

	showDialogSlot();

	messageDialog_->setTitle(title);
	messageDialog_->setMessage(message);
	messageDialog_->setIcon(iconKey);
	messageDialog_->setSuccess(true);
	messageDialog_->setReason(L"");

	messageDialog_->show();
	messageDialog_->raise();
	messageDialog_->activateWindow();
}

void MainWindow::answerFightActionReport(const fight_action_report & report) {
	// Do not reset waiting for update response here, this is not answer to request
	setWaitingForUpdateFortressResponse(false);
	fightWidget_->fightActionReport(report);
}

void MainWindow::answerFightProgressReport(const fight_progress_report & report) {
	// Do not reset waiting for update response here, this is not answer to request
	fightWidget_->fightProgressReport(report);
}

void MainWindow::answerBuildNewBaseShell(id_t selfFortressId, BaseBuildingResult result, unsigned long long newTitan) {
	setWaitingForUpdateFortressResponse(false);
	buildWidget_->answerBuildNewBaseShell(selfFortressId, result, newTitan);

	if (result == BBR_SHELL_BUILT) {
		showMessage(L"Postavení nové základny", L"Zahájení stavby nové základny začalo úspěšně.", GAME_ICON_BASE);
	}
	else {
		std::wstring reason;

		switch (result) {
		case BBR_INVALID_PARAMS:
			reason = L"Nezadal jsi správné parametry.";
			break;
		case BBR_NOT_ENOUGH_TITANIUM:
			reason = L"Nevložil jsi dostatek titanu.";
			break;
		case BBR_NO_PLANET_IN_RANGE:
			reason = L"V dosahu stavby není žádná planeta.";
			break;
		case BBR_UNKNOWN_FAIL:
			reason = L"Příčina není známa, zřejmě se jedná o chybu na serveru.";
			break;
		}

		showWarning(L"Postavení nové základny", L"Zahájení stavby nové základny selhalo.", GAME_ICON_BASE, reason);
	}
}

void MainWindow::answerAvailableFortressClasses(id_t selfFortressId, const std::list<fortress_class_simple_data> & shipClasses, const std::list<fortress_class_simple_data> & baseClasses) {
	setWaitingForUpdateFortressResponse(false);
	buildWidget_->answerAvailableFortressClasses(selfFortressId, shipClasses, baseClasses);
}

void MainWindow::answerFortressClassData(const fortress_class_complex_data & data) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(BUILD)) {
		buildWidget_->answerFortressClassData(data);
	}
	else if (currentState_.isInState(BASE_SECTION, BASE_HANGARS)) {
		detailsWidget_->ui_.hangarWidget->shipTypeSynchronize(data);
	}
}

void MainWindow::fortressClassDetailsSlot(id_t fortressClassId) {
	commandClient_->fortressClassData(fortressClassId);
}

void MainWindow::buildNewBaseShellSlot(id_t fortressId, id_t fortressClassId, unsigned long long titanium) {
	commandClient_->buildNewBaseShell(fortressId, fortressClassId, titanium);	
}

void MainWindow::answerFortressesBuildInformation(const std::list<fortress_build_information> & ships, const std::list<fortress_build_information> & bases) {
	setWaitingForUpdateFortressResponse(false);
	buildWidget_->setOwnedFortresses(ships, bases);
}

void MainWindow::answerFortresses(const std::vector<SimpleItem> & fortresses) {
	setWaitingForUpdateFortressResponse(false);
	tradeWidget_->setOwnedFortresses(fortresses);
}

void MainWindow::conquerSlot(id_t selfFortressId, id_t partnerFortressId) {
	commandClient_->conquerFortress(selfFortressId, partnerFortressId);
}

void MainWindow::tradeFromBuildSlot(id_t selfFortressId, id_t partnerFortressId) {
	commandClient_->sendTradeInvitation(selfFortressId, partnerFortressId);
}

void MainWindow::answerConquerFortress(const ConquerResultData & data) {
	setWaitingForUpdateFortressResponse(false);
	buildWidget_->answerConquerFortress(data);

	if (data.isConquered) {
		showMessage(L"Ovládnutí pevnosti", L"Pevnost byla úspěšně ovládnuta", GAME_ICON_CONQUER);
	}
	else {
		std::wstring reason;

		switch (data.addingResult) {
		case FAR_DONE:
			reason = L"Pevnost byla úspěšně zabrána";
			break;
		case FAR_NOT_ENOUGH_BIONODES:
			reason = L"Pevnost nelze přidat do sítě počítačů hráče, protože na to nemá dost biouzlů";
			break;
		case FAR_MAINFRAME_NOT_MOUNTED:
			reason = L"Cílová pevnost nemá namontovaný mainframe";
			break;
		case FAR_MAINFRAME_ENERGY_LACK:
			reason = L"V cílové pevnosti není dost energie";
			break;
		case FAR_FORTRESS_ALREADY_OWNED:
			reason = L"Cílovou pevnost už někdo vlastní a kontroluje";
			break;
		case FAR_OUT_OF_RANGE:
			reason = L"Cílová pevnost není v dosahu";
			break;
		case FAR_NULL_FORTRESS:
			reason = L"Parametrem je nulový pointer";
			break;
		}

		showWarning(L"Ovládnutí pevnosti", L"Pevnost se nepodařilo ovládnout", GAME_ICON_CONQUER, reason);
	}
}

void MainWindow::submitRegistrationSlot(const RegistrationData & data) {
	if (data.username == ADMIN_LOGIN) {
		showWarning(L"Přihlášení ke hře", L"Zadal jsi zakázané uživatelské jméno, žádný hráč nemůže mít uživatelské jméno admin", GAME_ICON_INVITATION);
		return;
	}

	if (commandClient_->isActive()) {
		commandClient_->disconnectFromServer();		
	}

	clearPlayerState();

	currentState_.changeMainState(REGISTRATION);

	LoginDetails login;
	login.name = data.username;
	login.password = data.password;
	login.server = data.server;
	login.port = data.port;

	ui_.loggedWidget->setLogin(login);	

	commandClient_->connectToServer(data.server, data.port);
	commandClient_->registerPlayer(data);
}

void MainWindow::addAccommodationsSlot(unsigned long count, accommodation_type accommodationType) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::addAccommodationsSlot(unsigned long count, accommodation_type accommodationType)")) {
		return;
	}

	commandClient_->fortressAddAccommodations(currentState_.getCurrentFortress().id, count, accommodationType);
}

void MainWindow::addCrewSlot(unsigned long able, unsigned long wounded, crew_type crewType) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::addCrewSlot(unsigned long able, unsigned long wounded, crew_type crewType)")) {
		return;
	}

	commandClient_->fortressAddCrew(currentState_.getCurrentFortress().id, able, wounded, crewType);
}

void MainWindow::removeCrewSlot(unsigned long able, unsigned long wounded, crew_type crewType) {
	if (!assertFortressExistence(
		"Not active fortress in method "
		"void MainWindow::removeCrewSlot(unsigned long able, unsigned long wounded, crew_type crewType)")) {
		return;
	}

	commandClient_->fortressRemoveCrew(currentState_.getCurrentFortress().id, able, wounded, crewType);
}

void MainWindow::answerFortressAddAccommodations(id_t fortressId, unsigned long count, accommodation_type accommodationType) {
	setWaitingForUpdateFortressResponse(false);

	wstringstream wss;
	wss << count;

	showMessage(L"Přidání nové místnosti", L"Přidání nové místnosti proběhlo úspěšně. Celkem bylo přidáno " + wss.str() + L" místností. ", GAME_ICON_ACCOMMODATIONS); 

	if (currentState_.isInState(SHIP_SECTION, SHIP_UBICATION) || currentState_.isInState(BASE_SECTION, BASE_UBICATION)) {
		if (currentState_.getCurrentFortress().id == fortressId) {
			commandClient_->updateFortressAccommodationsInformation(fortressId);
		}
	}
}

void MainWindow::answerFortressAddAccommodationsFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Přidání nové místnosti", L"Přidání nové místnosti se nepodařilo.", GAME_ICON_ACCOMMODATIONS, reason); 
}

void MainWindow::answerFortressAddCrew(id_t fortressId, unsigned long able, unsigned long wounded, crew_type crewType) {
	setWaitingForUpdateFortressResponse(false);

	wstringstream ableStream;
	ableStream << able;

	wstringstream woundedStream;
	woundedStream << wounded;

	showMessage(L"Přidání nového člena posádky", L"Přidání nového člena posádky proběhlo úspěšně. Celkem bylo přidáno " + ableStream.str() + L" zdravých a " + woundedStream.str() + L" zraněných členů. ", GAME_ICON_CREW); 

	if (currentState_.isInState(SHIP_SECTION, SHIP_CREW) || currentState_.isInState(BASE_SECTION, BASE_CREW)) {
		if (currentState_.getCurrentFortress().id == fortressId) {
			commandClient_->updateFortressCrewInformation(fortressId);
		}
	}
}

void MainWindow::answerFortressAddCrewFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Přidání nového člena posádky", L"Přidání nového člena posádky se nepodařilo.", GAME_ICON_CREW, reason); 
}

void MainWindow::answerFortressRemoveCrew(id_t fortressId, unsigned long able, unsigned long wounded, crew_type crewType) {
	setWaitingForUpdateFortressResponse(false);

	wstringstream ableStream;
	ableStream << able;

	wstringstream woundedStream;
	woundedStream << wounded;

	showMessage(L"Odebrání člena posádky", L"Odebrání člena posádky proběhlo úspěšně. Celkem bylo odebráno " + ableStream.str() + L" zdravých a " + woundedStream.str() + L" zraněných členů. ", GAME_ICON_CREW); 

	if (currentState_.isInState(SHIP_SECTION, SHIP_CREW) || currentState_.isInState(BASE_SECTION, BASE_CREW)) {
		if (currentState_.getCurrentFortress().id == fortressId) {
			commandClient_->updateFortressCrewInformation(fortressId);
		}
	}
}

void MainWindow::answerFortressRemoveCrewFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Odebrání člena posádky", L"Odebrání člena posádky se nepodařilo.", GAME_ICON_CREW, reason); 
}

void MainWindow::ownedFortressesSlot() {
	commandClient_->playerFortresses();
}

void MainWindow::answerLogin() {
	if (currentState_.isInState(REGISTRATION)) {
		showMessage(L"Registrace do hry", L"Registrace do hry proběhla úspěšně", GAME_ICON_INVITATION);

		loginWidget_->addConnection(ui_.loggedWidget->getLogin());
		currentState_.changeMainState(MAIN_NONE);
	}

	if (currentState_.isInState(REGISTRATION) ) {
		hideAllWidgets();

		ui_.mainMenuPanel->setVisible(true);		
		ui_.loggedWidget->setStatus(true);
		hideLoginPanel();

		clearState();
	}
	else {
		ui_.mainMenuPanel->setVisible(true);		
		ui_.loggedWidget->setStatus(true);
		hideLoginPanel();

		if (ui_.loggedWidget->isLoginDifferentFromLastOne()) {
			clearState();
		}
		else {
			restoreClientState();
		}
	}

	if (!currentState_.isInState(REGISTRATION)) {
		// If it is after login or reconnection, update attack information
		commandClient_->playerFortressesAttackInformation();
	}

	commandClient_->gameSecondsPerActualSecond();
}

void MainWindow::clearState() {
	detailsWidget_->clearState();
	chatWidget_->clearState();
	fightWidget_->clearState();
	buildWidget_->clearState();
	tradeWidget_->clearState();
}

void MainWindow::restoreClientState() {
	switch (currentState_.mainState) {
	case SHIP_SECTION:		
		updateShipSection();
		showDetailsWidget();
		break;
	case BASE_SECTION:
		updateBaseSection();
		showDetailsWidget();
		break;
	case TRADE:
		showTrade();
		break;
	case FIGHT:
		showFight();
		break;
	case BUILD:
		showBuild();
		break;
	}
}

void MainWindow::answerGameSecondsPerActualSecond(unsigned long value) {
	setGameSecondsPerActualSecond(value);
}

void MainWindow::answerLoginFAIL(const std::string & reason) {
	showWarning(L"Přihlášení uživatele", L"Přihlášení uživatele se nezdařilo", GAME_ICON_INVITATION, reason);
}

void MainWindow::answerRegistration(const RegistrationResult & result) {
	if (result.addingResult == PAR_OK) {
		showMessage(L"Registrace nového hráče", L"Registrace nového hráče proběha úspěšně. Byl jsi rovnou přihlášen.", GAME_ICON_INVITATION);
	}
	else {
		std::wstring reason;
		switch (result.addingResult) {
		case PAR_LOGIN_ALREADY_EXISTS:
			reason = L"Hráč se zadaným uživatelským jménem už existuje";
			break;
		case PAR_NAME_ALREADY_EXISTS:
			reason = L"Hráč se zadaným ménem už existuje";
			break;
		case PAR_INTERNAL_ERROR:
			reason = L"Interní chyba serveru";
			break;
		}

		showWarning(L"Registrace nového hráče", L"Registrace nového hráče se nezdařila", GAME_ICON_INVITATION, reason);
	}
}

void MainWindow::answerRenameFortressFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Přejmenování pevnosti", L"Přejmenování pevnosti se nezdařilo. ", GAME_ICON_SHIP, reason);
}

void MainWindow::answerRenameFortress(id_t fortressId, const std::string & newName) {
	setWaitingForUpdateFortressResponse(false);

	if (currentState_.isInState(SHIP_SECTION)) {
		commandClient_->playerShips();
	}
	else if (currentState_.isInState(BASE_SECTION)) {
		commandClient_->playerBases();
	}

	showMessage(L"Přejmenování pevnosti", L"Přejmenování pevnosti proběhlo úspěšně. ", GAME_ICON_SHIP);
}

void MainWindow::renameFortressSlot() {
	if (!currentState_.hasCurrentFortress()) {
		return;
	}

	showInputDialog(currentState_.getCurrentFortress());
}

void MainWindow::submitInputDialogSlot() {
	std::string newName = inputDialog_->getInputString();
	inputDialog_->accept();

	commandClient_->renameFortress(currentState_.getCurrentFortress().id, newName);

	hideDialogSlot();
}

void MainWindow::cancelInputDialogSlot() {
	inputDialog_->accept();
	hideDialogSlot();
}

void MainWindow::rejectDialogSlot() {
	hideDialogSlot();
}

void MainWindow::createInputDialog() {
	inputDialog_ = new InputDialog(this);
																						   
	bool connected = true;
	connected = connected && connect(inputDialog_, SIGNAL(submitSignal()), this, SLOT(submitInputDialogSlot()));
	connected = connected && connect(inputDialog_, SIGNAL(cancelSignal()), this, SLOT(cancelInputDialogSlot()));
	connected = connected && connect(inputDialog_, SIGNAL(rejected()), this, SLOT(rejectDialogSlot()));
	assert(connected && "Signals not connected");

	inputDialog_->setWindowFlags(Qt::SplashScreen);
}

void MainWindow::showInputDialog(const SimpleItem & fortress) {
	if (inputDialog_ == NULL) {
		createInputDialog();
	}

	showDialogSlot();

	wstringstream ws;
	ws << fortress.name.c_str();

	inputDialog_->setTitle(L"Přejmenování pevnosti");
	inputDialog_->setMessage(L"Zadej nové jméno pevnosti " + ws.str());
	inputDialog_->setInputLabel(L"Nové jméno");

	inputDialog_->show();
	inputDialog_->raise();
	inputDialog_->activateWindow();
}

void MainWindow::answerHangarBuildItem(id_t fortessId, id_t hangarId, const std::string & result) {
	setWaitingForUpdateFortressResponse(false);

	if (result == PROTOCOL_HANGAR_ICR_OK) {
		showMessage(L"Postavení předmětu v hangáru", L"Postavení předmětu v hangáru proběhlo úspěšně ", GAME_ICON_HANGARS);
	}
	else {
		showWarning(L"Postavení předmětu v hangáru", L"Postavení předmětu v hangáru se nezdařilo ", GAME_ICON_HANGARS, result);
	}
}

void MainWindow::answerHangarBuildItemFAIL(id_t fortressId, id_t hangarId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Postavení předmětu v hangáru", L"Postavení předmětu v hangáru se nezdařilo ", GAME_ICON_HANGARS, reason);
}

void MainWindow::answerHangarCancelItem(id_t fortressId, id_t hangarId) {
	setWaitingForUpdateFortressResponse(false);

	showMessage(L"Postavení předmětu v hangáru", L"Zrušení stavění předmětu v hangáru proběhlo úspěšně ", GAME_ICON_HANGARS);

	if (!currentState_.isInState(BASE_SECTION, BASE_HANGARS)) {
		return;
	}

	if (!(currentState_.getCurrentFortress().id == fortressId)) {
		return;
	}

	if (!(detailsWidget_->ui_.hangarWidget->getSelectedHangarID() == hangarId)) {
		return;
	}	

	commandClient_->updateBaseHangarsInformation(fortressId, hangarId, detailsWidget_->ui_.hangarWidget->getSelectedPatternName());
}

void MainWindow::answerHangarCancelItemFAIL(id_t fortessId, id_t hangarId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Zrušení stavění předmětu v hangáru", L"Zrušení stavění předmětu v hangáru se nezdařilo ", GAME_ICON_HANGARS, reason);
}

void MainWindow::answerHangarBuildShip(id_t fortessId, id_t hangarId, const std::string & result) {
	setWaitingForUpdateFortressResponse(false);

	if (result == PROTOCOL_HANGAR_ICR_OK) {
		showMessage(L"Postavení lodě v hangáru", L"Postavení lodě v hangáru proběhlo úspěšně ", GAME_ICON_HANGARS);
	}
	else {
		showWarning(L"Postavení lodě v hangáru", L"Postavení lodě v hangáru se nezdařilo ", GAME_ICON_HANGARS, result);
	}
}

void MainWindow::answerHangarBuildShipFAIL(id_t fortressId, id_t hangarId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Postavení lodě v hangáru", L"Postavení lodě v hangáru se nezdařilo ", GAME_ICON_HANGARS, reason);
}

void MainWindow::answerUpdateFortressSensors(id_t fortressId,const sensors_data & sensors, const sensors_data & lrSensors) {
	setWaitingForUpdateFortressResponse(false);
	detailsWidget_->ui_.sensorsWidget->setState(sensors, lrSensors);
}

void MainWindow::answerUpdateFortressSensorsFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Aktualizace senzorů", L"Aktualizace senzorů se nezdařila ", GAME_ICON_SENSORS, reason);
}

void MainWindow::answerUpdateFortressCloaking(id_t fortressId, const cloaking_data & data) {
	setWaitingForUpdateFortressResponse(false);
	detailsWidget_->ui_.cloakingWidget->setState(data);
}

void MainWindow::answerUpdateFortressCloakingFAIL(id_t fortressId, const std::string & reason) {
	setWaitingForUpdateFortressResponse(false);
	showWarning(L"Postavení lodě v hangáru", L"Postavení lodě v hangáru se nezdařilo ", GAME_ICON_CLOAKING, reason);
}

void MainWindow::updateAttackWarningsSlot(const std::map<id_t, fortress_under_attack_data> & fortresses) {
	ui_.warningEdit->clear();

	for (std::map<id_t, fortress_under_attack_data>::const_iterator it = fortresses.begin(); it != fortresses.end(); ++it) {
		QString multiplicatorSuffix;

		if (it->second.attackerCount < 1) {
			continue;
		}

		if (it->second.attackerCount > 1) {
			multiplicatorSuffix = " x" + QString::number(it->second.attackerCount);
		}

		ui_.warningEdit->append("<strong style=\"color: rgb(170, 45, 45);\">" + QString::fromLocal8Bit(it->second.fortressName.c_str()) + multiplicatorSuffix + "</strong>");
	}
}

void MainWindow::removeFortressSlot(id_t fortressId, const std::string & fortressName) {
	if (currentState_.isInState(SHIP_SECTION) && currentState_.getCurrentFortress().id == fortressId) {
		currentState_.changeMainState(MAIN_NONE);
		hideAllWidgets();
	}

	if (currentState_.isInState(BASE_SECTION) && currentState_.getCurrentFortress().id == fortressId) {
		currentState_.changeMainState(MAIN_NONE);
		hideAllWidgets();
	}

	if (currentState_.shipSectionState.getCurrentShipId() == fortressId) {
		currentState_.shipSectionState.changeState(SHIP_NONE);
	}

	if (currentState_.isInState(TRADE)) {
		// TODO Remove from trade
	}

	if (currentState_.isInState(BUILD)) {
		// TODO Remove from build
	}

	if (currentState_.isInState(FIGHT)) {
		// Fight takes care by itself
	}

	showMessage(
		QString::fromUtf16(L"Pevnost byla zničena"),
		QString::fromUtf16(L"Tvoje pevnost ") + QString::fromLocal8Bit(fortressName.c_str()) + QString::fromUtf16(L" byla zničena!"), 
		GAME_ICON_SHIP);
}