#include "UGStaticData.h"


UGStaticData::UGStaticData():HPLBasicStaticData(){
	// 設定ファイル読み込み
	setting = new UGSetting();

	// キー入力等インプット設定
	std::map<int, int> keyMap = HPLKeyMapTool::loadKeyMapFromFile("data/KeyMap.txt");
	getInputManager()->getKeyInput()->setKeyMap(keyMap);

	// マップマネージャ
	/*HPLNameListManager* mapNameListMgr = new HPLNameListManager("data/MapList.txt");
	this->setMapNameListManager(mapNameListMgr);
	*/
	mapManager = new HPLMapManager("data/MapFileList.txt");

	
	getBlockManager()->setBlockSize(32);

	objectManager = NULL;

	screenFormat.width = setting->windowWidth;
	screenFormat.height = setting->windowHeight;
	screenFormat.colorBitPerPixel = setting->bitPerPixel;
	screenFormat.videoFlags = SDL_HWSURFACE;

	getGame()->setCheat(false);

	objectPlacer = new UGObjectPlacer();


	// マップデータ読み込み
	mapData = new HPLMapData("data/maps/MapItemList.txt");

	eventManager = new UGEventManager();

	eventPack = NULL;

	// EventPack読み込み
	setEventPackManager(new HPLEventPackManager("data/event/EventPack.txt"));

	// ※EventBoxはステージごとの読み込み
}

UGStaticData::~UGStaticData(){
	delete objectManager;
	delete eventManager;
}

void UGStaticData::loadTexture(){

	this->imageSetContainer = new HPLImageSetContainer("data/image/ImageSetFileList.dat",
		getImageManager(), 255,255,255);
	// load
	//this->imageStock = new HPLImageStock("data/ImageList.txt", this->getImageManager());

	//commonSpriteList = new HPLSpriteList("data/CommonSpriteList.txt");

	//this->playerSpriteList = new HPLSpriteList("data/PlayerSpriteList.txt");
	//this->enemySpriteList = new HPLSpriteList("data/EnemySpriteList.txt");

	// sdl kanji フォント読み込み
	sdlkanji = new HPLSDLKanjiManager();
	sdlkanji->setFont("data/font/shnmk16.bdf", "data/font/shnm8x16a.bdf", 16,0);

	objectManager = new UGObjectManager();

	getBlockManager()->setupBlock("data/maps/Block000.txt",
		getSprite(UGEnum::SpriteType::Common)->clone());


	createMixerManager("data/se/SEList.txt", "data/music/MusicList.txt");
}


void UGStaticData::doEvent(){
	setRunning(eventManager->doEvent());


	///////
	// その他システム動作

	/////
	// ワールド！キー
	if(this->getInputManager()->isPressedNow(UGEnum::KeyMap::J)){
		this->getGame()->setTheWorld(!this->getGame()->isTheWorld());
	}

	////
	// イベントスキップキー
	if(this->getGame()->isScenario() == true){
		if(this->getInputManager()->isPressedNow(UGEnum::KeyMap::H)){
			this->getGame()->setScenario(false);
			eventPack->setActive(false);
		}
	}
}

void UGStaticData::checkEvent(){

	//////
	// イベント・シナリオ実行
	bool isSkip = this->getGame()->isTheWorld() ||
		this->getGame()->isMenu() ||
		this->getGame()->isScenario();
	
//	if(isSkip == false){

		if(eventPack == NULL){
			/////
			//
			HPLVector center = this->getObjectManager()->getPlayer()->getCenter();

			HPLEventBox* box = this->getEventBoxManager()->getEventBox(center,
				staticData->getSetting()->tileSize);

			if(box != NULL){
				//////
				// 該当するBOXが見つかった
				//  ｰ>指定されたイベントパックを実行する

				int index = box->getIndex();

				////
				// イベントパック取得
				eventPack = getEventPackManager()->getEventPack(index);
			}
		}

		if(eventPack != NULL){

			if(eventPack->isActive() == true){
				getGame()->setScenario(true);

				////
				// イベント実行
				this->doEventPack();
			}else {
				eventPack = NULL;
				getGame()->setScenario(false);
			}
			
		}else{
			getGame()->setScenario(false);
		}
//	}
}


void UGStaticData::setupMap(int index){
	///////////
	// オブジェクト除去
	HPLMapManager* mapManager = staticData->getMapManager();
	std::string mapFilePathBase = mapManager->getMapFilePath(index);
	
	// 本体 csv
	std::string mapCSV = mapFilePathBase + std::string(".csv");
	
	// シナリオ
	//std::string mapESC = mapFilePathBase + std::string(".esc");

	std::string eventBoxFilePath("data/maps/NULL_EventBox.txt");

	std::string checkEventBoxFileExists = mapFilePathBase + std::string(".txt");
	if(HPLFile::isExists(checkEventBoxFileExists.c_str()) == true){
		eventBoxFilePath = checkEventBoxFileExists;

	}
	HPLEventBoxManager* boxManager = getEventBoxManager();
	if(boxManager != NULL){
		delete boxManager;
		boxManager = NULL;
	}
	setEventBoxManager(new HPLEventBoxManager(eventBoxFilePath.c_str()));


	//// シナリオをクリア
	//staticData->getScenarioManager()->clear();

	// オブジェクトをクリア
	staticData->getObjectManager()->clear();

	// ブロックをリセット
	AbstractBlockManager* blockManager = staticData->getBlockManager();

	/////////
	// マップロード
	blockManager->loadMatrix(mapCSV.c_str());

	int tileSize = staticData->getSetting()->tileSize;
	//HPLError::msg("hoge", MB_OK, "%d",tileSize);

	////////////////////
	// set scroller
	{
		HPLRect virRect(0,0,
			(float)(blockManager->getBlockMatrix()->getColumnSize() * tileSize),
			(float)(blockManager->getBlockMatrix()->getRowSize() * tileSize));

/*		HPLError::msg("hoge", MB_OK, "%d",
			blockManager->getBlockMatrix()->getColumnSize());
		HPLError::msg("hoge", MB_OK, "%d",
			blockManager->getBlockMatrix()->getRowSize());
		HPLError::msg("hoge", MB_OK, "%f,%f,%f,%f", virRect.getX(), virRect.getY(), virRect.getWidth(), virRect.getHeight());
		*/
		HPLScroller* scroller = staticData->getScrollManager()->getScroller(0);
		scroller->setVirtualRect(virRect);
	}


	UGPlayer* player = staticData->getObjectManager()->getPlayer();
	
	/////
	// プレイヤー状態異常解除
	player->setHeld(false);
	player->setBind(false);
	player->changeState(StateType::STAND);
	player->setHP(player->getHPMax());

	/////
	// オブジェクト配置
	objectPlacer->loadAndPlace(blockManager->getBlockMatrix(),
		getSetting()->tileSize,
		staticData->getMapData());

	
}

void UGStaticData::processFadeOut(){
	if(HPLBasicStaticData::processFadeOut(getSequence(UGEnum::SpriteType::Common, UGEnum::Common::FadeOut))){
		///////
		// シーン＆マップ変更
		if(nextScene != -1){
			getSceneManager()->setScene(nextScene);
		}

		if(nextMap != -1){
			setupMap(nextMap);
		}

	}
}


HPLRect UGStaticData::getGameRange(){
	HPLScroller* scroller = getScrollManager()->getScroller(0);


	HPLRect r = getSetting()->gameRange;
	r.setX(r.getX() - scroller->getVirtualRect().getX());
	r.setY(r.getY() - scroller->getVirtualRect().getY());
	return r;

}
HPLRect UGStaticData::getMerginedGameRange(){
	HPLScroller* scroller = getScrollManager()->getScroller(0);


	HPLRect r = getSetting()->merginedGameRange;
	r.setX(r.getX() - scroller->getVirtualRect().getX());
	r.setY(r.getY() - scroller->getVirtualRect().getY());
	return r;
}


void UGStaticData::doEventPack(){
	HPLError::assertIt(eventPack != NULL && eventPack->isActive(),
		"内部エラー：UGStaticData::doEventPack イベントパックがNULLまたは不活性のまま呼ばれた");
	
	HPLScenarioItem* item = eventPack->get();

	if(item == NULL){
		eventPack->setActive(false);
	}else{
		int r = 255, g = 255, b = 255;
		int fontID = 0;
		int stepY = 20;
		int maxLines = 5;
		int msgTop = 360;
		int maxCharLengthPerLine = 70;

		if(item->getType() == ScenarioType::TALK){
			//////
			// 立ちえ表示

			// left

			// right

			
		}else if(item->getType() == ScenarioType::EMOTION){
		}else if(item->getType() == ScenarioType::SELECT){
			b = 0;
		}else if(item->getType() == ScenarioType::MAP){
			
			startFadeOut(item->getMapScene(), item->getMapMap());

		}else if(item->getType() == ScenarioType::MUSIC){
		}else if(item->getType() == ScenarioType::SE){
		}else {
			/////
			// 
		}

		if(item->getType() == ScenarioType::MAP ||
			item->getType() == ScenarioType::MUSIC ||
			item->getType() == ScenarioType::SE
			){
				if(eventPack->next() == false){
					getGame()->setScenario(false);
				}

		}else if(item->getType() == ScenarioType::TALK ||
			item->getType() == ScenarioType::EMOTION ||
			item->getType() == ScenarioType::SELECT){

				// せりふフレーム
/*				HPLSDLImageTool::blitRotozoomSpriteLeftTop(
					0, 240,
					0,
					getSequence(UGEnum::SpriteType::Common,
						UGEnum::Common::TalkFrame),
					getImageManager(),
					getGraphics()->getScreen(),
					255);*/
				
				// せりふ表示
				std::map<int,int> left;
				left[ScenarioType::TALK] = 10;
				left[ScenarioType::EMOTION] = 100;
				left[ScenarioType::SELECT] = 50;
				
				this->getSDLKanjiManager()->drawTalkMessage(r, g, b, fontID, item->getMessageList(),
														stepY, maxLines,
														left[item->getType()],
														msgTop,
														maxCharLengthPerLine,
														getGraphics()->getScreen());	


				/////
				// キー処理
				if(getInputManager()->isPressedNow(UGEnum::KeyMap::A)){
					if(item->getType() == ScenarioType::SELECT){
						/////
						// selectのみ特殊
					}else{
						///
						// 次へ進める
						if(eventPack->next() == false){
							getGame()->setScenario(false);
						}
					}
				}
		}
	}
}

