/*
	AramakiOnline
	Copyright (C) 2008 superbacker

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

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

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

#include "World.h"
#include "tinyxml.h"
#include <wx/url.h>

bool World::initialized;
Model *World::sky;

World::World(uint16_t listenPort,const wxString &initNodeHost,uint16_t initNodePort) {
	if (!initialized) initialize();

	//ネットワークに接続
	network=new P2PNetwork(listenPort,initNodeHost,initNodePort);
	if (error=network->isError()) errorMessage="ネットワークへ接続/ネットワークの作成に失敗";

	//初期マップをロード
	map=new Map(wxT("fountain.xml"));

	//初期位置を設定
	myCharacter=new MyCharacter(*network,*map);
	myCharacter->setPosition(Point3d(12,0,0.5));
	myCharacter->setDirection(180);

	//ネットワークに接続されていないと必ず失敗する
	if (!network->isError()) portCheck(listenPort);
}

World::~World() {
	delete network;
	delete myCharacter;
	delete map;
}

void World::initialize() {
	//空モデルをロード
	sky=new Model(wxT("sky.obj"));

	initialized=true;
}

void World::draw() const {
	//自機を描画
	myCharacter->draw();
	//ほかのキャラクタを描画
	network->drawCharacter();

	//空を描画
	glPushMatrix();
	//自機の動きにあわせてずらす
	glTranslated(myCharacter->getPosition().x,myCharacter->getPosition().y,myCharacter->getPosition().z);
	sky->draw();
	glPopMatrix();

	//マップを描画
	map->draw();
}

void World::changeMap(const wxString &mapXmlFileName) {
	delete map;
	map=new Map(mapXmlFileName);
	delete myCharacter;
	myCharacter=new MyCharacter(*network,*map);
}

void World::portCheck(uint16_t port) {
	wxURL url(wxString::Format("http://backeros.if.land.to/port_check.php?port=%u",port));

	if (url.IsOk()) {
		wxInputStream *inputStream;
		char buffer[2];

		if (!(inputStream=url.GetInputStream())) {
			errorMessage="ポートチェックに失敗";
			error=true;
			return;
		}

		inputStream->Read(buffer,2);

		//OKorNGが返される
		if (wxString::FromUTF8(buffer,2)!="OK") {
			errorMessage="ポートが開放されていません";
			error=true;
		}
	} else {
		errorMessage="ポートチェックに失敗";
		error=true;
	}
}
