//****************************************************************************************************
// Replay playback menu
//
// Library:
//		menuReplayPlayHandler			- Main menu flow.
//		makeMenuChoice					- Made menu choice task.
//		showRText						- Simple function to summon text on screen.
//		drawPlayerScreen				- Draws the BG
//		
//****************************************************************************************************

#include "script/thdcs/functions/function_loaddata.txt"
#include "script/thdcs/functions/const_sound.txt"

@Initialize {
	SetAutoDeleteObject(true);
	menuReplayPlayHandler;
	SetScriptResult("dummy");
}

@MainLoop { yield; }
@Finalize { } 

// Difficulty handler menu
task menuReplayPlayHandler { 
	
	// Draw
	let pSelScreen = drawPlayerScreen(imgPSelBg, BLEND_ALPHA);
	let topLogoBg = drawTexture(128, 32, menulogos, BLEND_ALPHA, 155, 0, 0, 512, 128);
	let topLogo = drawTexture(128, 64, menulogos, BLEND_ALPHA, 255, 0, 512, 512, 640);
	
	// Load the replay list and store
	LoadReplayList;

	let replayListIndex = GetValidReplayIndices;
	let maxPage = 1;						        // max pages for replays
	let maxList = 15;						        // max replays per page
	let replayArray = [ID_INVALID];			        // Array to hold all the replays loaded
	let pageArray = [ID_INVALID];
	let pageNum = 0;						        // current page displayed
	let replayChoice = 1;					        // current replay choice
	
	// Calculate how many pages are needed to display
	maxPage = length(replayListIndex) / maxList;
	
	// Count how many replays are found in the folder.
	let countReplay = length(replayListIndex);
	
	// Ascent the replaylist and fill in with blanks.
	ascent(i in 0..maxList) {
		replayArray = replayArray ~ [showRText(16, 72+25*i, "No." ~ IntToString(i+1) ~ " " ~ "-------- --/--/-- --:-- ------- ------- --- ---% ---")];
	}	

	SetCommonData("isReplay",false);

	while(GetVirtualKeyState(VK_OK) != KEY_FREE) { yield; }

	if(!ObjSound_IsPlaying(BGM_TITLE)) { PlayMusic(BGM_TITLE); }

	loop {
		// Ascent the replaylist and fill it now with the details from each replay in the replay folder.
		ascent(i in 0..length(replayListIndex)) {
			// If there is a valid replay found, draw it on the corresponding index row. 
			if(IsValidReplayIndex(replayListIndex[i])) {
				let repUser = " " ~ vtos("-8s", GetReplayInfo(replayListIndex[i], REPLAY_USER_NAME)) ~ " ";				            // Get the username 8 char max.
				let repDate = " " ~ GetReplayInfo(replayListIndex[i], REPLAY_DATE_TIME) ~ " ";							            // Get the date + time in one go.
				let repChar = " " ~ GetReplayInfo(replayListIndex[i], REPLAY_PLAYER_NAME) ~ " ";						            // Get the player character, this/ is influenced by #ReplayName[] in player scripts.
				let preString = SplitString(GetReplayInfo(replayListIndex[i], REPLAY_COMMENT), "::");						        // Get replay comment and turn it into array splitting :: as index
				let repLevel = " " ~ preString[0] ~ " ";																	        // Get the difficulty level.
				let repMode = " " ~ preString[1] ~ " ";																		        // Get the mode
				let repStg = "";

				if(repMode == "Spl Prac") {
				    repStg = " " ~ "Spell No. " ~ preString[2] ~ " ";                                                               // If this is a spell practise replay, display card number
                } else {
                    repStg = " " ~ preString[2] ~ " ";                                                                              // Otherwise display stage number.
                }

				let repSlow = " " ~ vtos("0.1f", (60 - round(GetReplayInfo(replayListIndex[i], REPLAY_FPS_AVERAGE))) / 100) ~ "%";	// Get the slowdown

				// Display the full data of the replay file by using the previous set variables
				ObjText_SetText(replayArray[replayListIndex[i] - 0],
					"No."
					~IntToString(replayListIndex[i]) ~ " "
					~repUser ~ " "
					~repDate ~ " "
					~repChar ~ " "
					~repLevel ~ " "
					~repStg ~ " "
					~repSlow ~ " "
					~repMode ~ " "
				);
			}
		}	

		// Animating the replay items (selected = bright, otherwise dark/dim)
		ascent(i in 0..length(replayArray)) {
			if(i == replayChoice) {
				ObjRender_SetColor(replayArray[replayChoice], 128, 192, 255);
			} else {
				ObjRender_SetColor(replayArray[i], 64, 64, 64);
			}
		}

		if(GetVirtualKeyState(VK_UP) == KEY_PUSH || GetVirtualKeyState(VK_UP) == KEY_HOLD) { 
			PlaySFX(SFX_MENPICK);	
			if(replayChoice > 1) { replayChoice--; } 
			loop(5) { yield; } 
		}
		if(GetVirtualKeyState(VK_DOWN) == KEY_PUSH || GetVirtualKeyState(VK_DOWN) == KEY_HOLD) { 
			PlaySFX(SFX_MENPICK);	
			if(replayChoice < maxList) { replayChoice++; } 
			loop(5) { yield; } 
		}
		if(GetVirtualKeyState(VK_OK)==KEY_PUSH) { 
			PlaySFX(SFX_OK00);

			if(IsValidReplayIndex(replayChoice)) {
				// Start scanning the entire replay list to see if choice matches the index
				ascent(j in 0..length(replayListIndex)) { 
					if(replayChoice == replayListIndex[j]) { 
						// Get the replay file path and store in var, then pass it on to the task.
						let replayPlayInfo = GetReplayInfo(replayListIndex[j], REPLAY_FILE_PATH);
						makeMenuChoice(replayListIndex[j]);	
					}				
				}
				break;
			}
			
		}
		if(GetVirtualKeyState(VK_CANCEL) == KEY_PULL) { 
			PlaySFX(SFX_MENCANCEL);

			SetCommonData("isReplay", false);
			SetScriptResult("CANCEL"); 
			CloseScript(GetOwnScriptID);

			break;
		} 
		yield;	
	}
	ascent(i in 0..length(replayArray)) { Obj_Delete(replayArray[i]); } 	
	Obj_Delete(pSelScreen);
	Obj_Delete(topLogoBg);
	Obj_Delete(topLogo);
}

task makeMenuChoice(replay) {
	if(GetAreaCommonData("game","menuFlow",0) != 3) {
		fadeTransitionScreen; fadeTransitionScreen;
		loop(60) { yield; }
	}

	let getStgIndex = GetReplayInfo(replay, REPLAY_STAGE_INDEX_LIST);
	let getReplayFile = GetReplayInfo(replay, REPLAY_FILE_PATH);
	
	SetCommonData("replayStgIndex", getStgIndex[0]);
	SetCommonData("replayFile", getReplayFile);
	
	// Get the replay comment and convert it into an array using :: as element split identifier. 
	let replayComment = SplitString(GetReplayInfo(replay, REPLAY_COMMENT), "::");
	let replayDifficulty = 0;

	if(replayComment[0] == "Normal") { replayDifficulty = 0; } 
	else if(replayComment[0] == "Hard") { replayDifficulty = 1; } 
	else if(replayComment[0] == "Lunatic") { replayDifficulty = 2; }

	SetCommonData("replayDifficulty", replayDifficulty);
	SetCommonData("replayMode", replayComment[1]);
	SetCommonData("replayCardNum", atoi(replayComment[2]));
	
	if(replayComment[1] == "Spl Prac") { 
		SetCommonData("tryStage", atoi(replayComment[3]));
		SetCommonData("tryCard", atoi(replayComment[4]));
		SetCommonData("tryDifficulty", atoi(replayComment[5]));
	}

	SetCommonData("isReplay", true);
	
	// get the path var and load and launch the script
	let path = "script/thdcs/menu/pack_stage.txt";	
	let id = LoadScript(path);
	StartScript(id);	

	// Halt this script while busy
	while(!IsCloseScript(id)) {
		yield;
	}		
	
	let result = GetScriptResult(id);	
	if(result == "ENDREPLAYPLAY") {
	    SetCommonData("isDialogue", false);
        musicRestartEnable(GetAreaCommonData("sound", "song", 0), 0);
        StopAllMusic(0);
        StopAllSFX(0);
	    menuReplayPlayHandler;
    }
}

// Function to draw text on the screen.
function showRText(x, y, txt) {
	let obj = ObjText_Create;
	
	ObjText_SetText(obj, txt);
	ObjText_SetFontType(obj,"MeiryoKe_PGothic");
	Obj_SetRenderPriorityI(obj, 100);
	ObjText_SetFontSize(obj, 16);
	ObjText_SetSidePitch(obj, -2);
	ObjText_SetMaxWidth(obj, 640);
	ObjText_SetMaxHeight(obj, 480);
	ObjText_SetFontColorTop(obj, 255, 255, 255);
	ObjText_SetFontColorBottom(obj, 255, 255, 255);
	ObjText_SetFontBorderType(obj, BORDER_SHADOW);
	ObjText_SetFontBold(obj,false);	
	ObjText_SetFontBorderWidth(obj, 2);
	ObjText_SetFontBorderColor(obj, 0, 0, 0);
	ObjRender_SetColor(obj, 128, 128, 128);
	ObjRender_SetPosition(obj, x, y, 0);

	return obj
}

// Draws a texture (flexible)
function drawTexture(x, y, tex, blendType, alphaValue, left, top, right, bottom) {
	let obj = ObjPrim_Create(OBJ_SPRITE_2D);

	ObjPrim_SetTexture(obj, tex);
	ObjRender_SetBlendType(obj, blendType);
	ObjRender_SetAlpha(obj, alphaValue);
	Obj_SetRenderPriorityI(obj, 20);
	ObjSprite2D_SetSourceRect(obj, left, top, right, bottom);
	ObjSprite2D_SetDestCenter(obj);
	ObjRender_SetPosition(obj, x, y, 0);
	
	return obj;	
}

// Draws the title screen
function drawPlayerScreen(tex, blendType) {
	let obj = ObjPrim_Create(OBJ_SPRITE_2D);

	ObjPrim_SetTexture(obj, tex);
	ObjRender_SetBlendType(obj, blendType);
	ObjRender_SetAlpha(obj,205);
	Obj_SetRenderPriorityI(obj, 20);
	ObjSprite2D_SetSourceRect(obj, 0, 0, 640, 480);
	ObjSprite2D_SetDestRect(obj, 0, 0, 640, 480);
	
	return obj;	
}

// Draws the fade in/out wait screen between transitions.
task fadeTransitionScreen {
	let obj = ObjPrim_Create(OBJ_SPRITE_2D);
	let scrAlpha = 0;
	let scrScroll = 0;
	ObjPrim_SetTexture(obj,imgWaitScr);
	ObjRender_SetBlendType(obj,BLEND_ALPHA);
	ObjRender_SetAlpha(obj,scrAlpha);
	Obj_SetRenderPriorityI(obj,100);
	ObjSprite2D_SetSourceRect(obj,0,0,1024,1024);
	ObjSprite2D_SetDestRect(obj,0,0,1024,1024);

	loop(5) { ObjSprite2D_SetSourceRect(obj,0+scrScroll,0+scrScroll,1024+scrScroll,1024+scrScroll); scrScroll--; ObjRender_SetAlpha(obj,scrAlpha); scrAlpha+=255/5; yield; }
	loop(60) { ObjSprite2D_SetSourceRect(obj,0+scrScroll,0+scrScroll,1024+scrScroll,1024+scrScroll); scrScroll--; yield; }
	loop(5) { ObjSprite2D_SetSourceRect(obj,0+scrScroll,0+scrScroll,1024+scrScroll,1024+scrScroll); scrScroll--; ObjRender_SetAlpha(obj,scrAlpha); scrAlpha-=255/5; yield; }

	Obj_Delete(obj);
}