-- level complete events


T_LEVELS_LEFT = Localize ("%d Days Remaining.");
T_LEVELS_LEFT_ONE = Localize ("One Day Remaining.");
T_LEVELS_LEFT_NONE = Localize ("Today is the day.");
T_RANK = Localize ("Rank: %s");
T_TIME_LEFT = Localize ("Time left: %s%%");

timer = 0;
talisman_parts = 0;
lev_num_completed = 1;

starson = 0;
starsrequired = 0;
interval1 = 0;
starlit = 0;
complete = 0;
rankvalue = 0;
timer2 = 0;

function OnLoad ()
	CacheSound ("music/levelcomplete.ogg");
	CacheSound ("music/trophy.ogg");
	CacheFX ("fxs/panel-medium-outlines.lua");
	NX_GetBitmap("ui/gfx/starbig-on.png");
	SetProperty ("time_left:label.text", string.format(T_TIME_LEFT, 0));
end;


function SetTip ()
	
	num_tips = DM_GetArraySize ("xml/tips.xml", "gameplay_tips");
	Print ("Num tips: " ..num_tips .."\n");
	
	lev_num = GetGameValue ("level_number");
	
	index = math.random (1, num_tips)-1;
	while (tonumber(DM_GetValue ("xml/tips.xml", "gameplay_tips", index, "min_level")) > lev_num) do
		index = math.random (1, num_tips)-1;
	end;
	tip = DM_GetValue ("xml/tips.xml", "gameplay_tips", index, "text");
	--Print ("tips: " ..tip .."\n");
	SetProperty ("tip:label.text", tip);
end;

function ColorBg ()
	lev_num_completed = GetGameValue ("level_number")-1;
	episode = math.floor ((lev_num_completed-1) / 7)+1;
	
	local minor = lev_num_completed - (episode-1) * 7;
	
	local bm = string.format("worldmap/backgrounds/bg-%04d.jpg", episode);
					
	--Azkend_BitmapColorSepia ("GAME_BACKGROUND", bm, 1);
	Azkend_BitmapCreateMask ("MENU_BACKGROUND", episode, minor, "CUMULATIVE|PARTS");
	Azkend_BitmapDrawInto ("MENU_BACKGROUND", "TEMP_SCREEN");

	--Azkend_BitmapCreateMask ("TEMP", episode, minor, "CUMULATIVE|PARTS");
	--Azkend_BitmapDrawInto ("TEMP", "GAME_BACKGROUND");
end;


color_akey = 0;
color_offset = 0;
color_phase = 0;
		
function UpdateColoring ()
	local t = math.min (1, color_akey);
	local t2 = math.min (1, color_akey-1);
	
	Azkend_SetColoringPhase (math.min (1, color_akey-1.3));
	
	color_offset = 600 * (1-math.cos (math.pi/2 * t));
	SetProperty ("talisman:position_offset.y", color_offset);
	--SetProperty ("panel:position_offset.y", offset);
	
	if (t2 > 0 and color_phase == 0) then
		ColorBg ();
		color_phase = 1;
		NX_PlaySound ("sfx/flower.ogg");
	end;
	
	if (color_akey > 4 and color_phase == 1) then
		color_phase = 2;
		OnClick ("Ok");
	end;

end;



function OnEnter ()
	SetProperty ("color:active", 1);
	
  SetProperty ("rank:label.text", string.format (T_RANK, DM_GetValue ("xml/ranks.xml", "ranks", 0, "rank")));	
   		
	color_akey = 0;
	color_phase = 0;
	UpdateColoring ();

	starson = 0;
	interval1 = 0;
	starsrequired = 0;
	starlit = 0;
	complete = 0;
	timer2 = 0;
	
	SetProfileVar ("StatLevelsCompleted", GetProfileVar ("StatLevelsCompleted")+1);
	
	SetProperty ("timeslider:slider.value",0.0);
	SetProperty ("timeslider:active", 0);
	SetProperty ("time_left:label.text", string.format(T_TIME_LEFT, 0));
	
	SetProperty ("/LevelCompleted:enter_trans_duration", 0.5);
	SetProperty ("/LevelCompleted:leave_trans_duration", 0.5);
	
	SetProperty ("a1:visible", Azkend_IsAchieved ("TIME"));
	SetProperty ("a2:visible", Azkend_IsAchieved ("LIGHTNING"));
	SetProperty ("a3:visible", Azkend_IsAchieved ("CONNECT"));
	SetProperty ("star2:blend_mode", "ADDITIVE");

	SetTip ();
		
	SetProperty ("level_short_name:label.text", GetGameValue ("level_short_name"));
	SetProperty ("level_long_name:label.text", GetGameValue ("level_long_name"));

	StopMusic (3.0); -- the parm is the fade out time
	PlaySound ("music/levelcomplete.ogg");
	 
	lev_num_completed = GetGameValue ("level_number"); 
	 
	-- !! level completed needs to add the level number OnEnter if the game has levels !!
	--    The game state should also be saved right here so that player won't lose
	--    any progress if s/he chooses to close the window at this point or whatver.
	level_number = GetGameValue ("level_number");
	the_last_level = GetGameValue ("number_of_levels");
  
	if (level_number == the_last_level) then
		-- set the level number one beyond the last to have the coloring work ok
		SetGameValue ("level_number", the_last_level+1);
		DeleteGameState ();	-- it was the last level, the game is completed
		game_completed = true;
	else
		-- set the next level
		SetGameValue ("level_number", level_number+1);
		SaveGameState ("WorldMap");		
		game_completed = false;
	end;
	
	
	--
	
	prev_akey = 0;
	
		
	lev_num = GetGameValue ("level_number");

	-- talisman parts before the addition
	talisman_parts = math.fmod (lev_num, 5)-1;
	talisman_num = math.floor ((lev_num_completed-1)/5);

	if (math.floor (math.fmod (lev_num_completed, 5)) == 0) then
		talisman_completed = true;
	else
		talisman_completed = false;
	end;
	
	if (lev_num_completed > 40) then
		talisman_completed = false;
	end;
	
	
--	SetProperty ("desc:label.text", string.format (T_PARTS_TO_DISCOVER, talisman_parts));


	last_day_of_the_week = false;
	if (math.floor (math.fmod (lev_num_completed, 7)) == 0) then
		last_day_of_the_week = true;
	end;

	
		
	if (lev_num_completed > 40) then
	
		levels_left = 70 - lev_num_completed;
		if (levels_left < 1) then
			SetProperty ("desc:label.text", T_LEVELS_LEFT_NONE);
		elseif (levels_left == 1) then
			SetProperty ("desc:label.text", T_LEVELS_LEFT_ONE);
		else
			SetProperty ("desc:label.text", string.format (T_LEVELS_LEFT, levels_left));
		end;
				
	else
		SetProperty ("desc:label.text", Azkend_GetPowerupName (talisman_num));
	end;



	-- TODO: make sure all strings are localized...
	local level_time = GetGameValue ("azkend_level_time");
	local level_time_max = GetGameValue ("azkend_level_time_max");
	--local time_left = string.format("%u", 100 * level_time / level_time_max);
	--SetProperty ("time_left:label.text", string.format(T_TIME_LEFT, time_left));
	--rankvalue = (1 - (level_time / level_time_max)) * (2-threshold);
	
	rankvalue = (1 - (level_time / level_time_max));
	--Print("Rankv "..rankvalue.."\n");
	starsrequired = rankvalue / 0.5;
	--Print("Rank "..starsrequired.."\n");
	if(starsrequired > 1) then
		starsrequired = 1;
	end;
	
	-- update the level rank in profile data if needed
	if (rankvalue >= 0.5) then
		local old_value = GetProfileVar ("LevRank"..lev_num_completed, "1");
		if (old_value == nil or old_value == "0") then
			SetProfileVar ("LevRank"..lev_num_completed, "1");
		end;
	end;
	
	SetProperty("rankstar0:label.bitmap", "ui/gfx/starbig-off.png");

	
	
	SetProperty ("/TalismanCompleted/talisman_name:label.text", Azkend_GetPowerupName (talisman_num));
	SetProperty ("/TalismanCompleted/talisman_desc:label.text", Azkend_GetPowerupDesc (talisman_num));
	SetProperty ("/TalismanCompleted/talisman_bitmap:label.bitmap", Azkend_GetPowerupBitmapBig (talisman_num));


	-- Azkend_string.format (T_PARTS_TO_DISCOVER, talisman_parts));
	--Azkend_SetTalismanSize (0);
	
	if (Azkend_AutoplayerActive ()) then
		if (lev_num > 60) then
			game_completed = false;
			SetGameValue ("level_number", 2);
			SaveGameState ("WorldMap");	
		end;
		talisman_completed = false;
		OnClick ("Ok");
	end;
	
end;

function OnLeave ()

	color_akey = 0;
	color_phase = 0;
	UpdateColoring ();	
end;


function OnClick (name)

	Print ("OnClick " .. name .. "\n");
--	SetTip ()

	if (name == "Menu") then
		starson = starsrequired;
		PushScreen ("GamePopMenu");
		return;
	end;



	if (name == "Ok") then
		if (game_completed) then
			SwitchScreen ("HiddenWorld");
			--SwitchScreen ("GameCompleted");
		else
			if (talisman_completed) then
				-- force select the new talisman
				index = Azkend_GetSlotPowerup (0);
				Azkend_UnselectPowerup (index);
				talisman_name = Azkend_GetPowerupID(talisman_num);
				Print ("Forcing talisman " .. talisman_name .. " active.....\n");
				Azkend_SelectPowerup ("Amulet_"..talisman_name);
				
				-- on last day lets just show the amulet and continue to hidden object game.
				-- on normal day we'll enter the shaman screen.
				if (not last_day_of_the_week) then
					SwitchScreen("Shaman");
				end;
				PushScreen ("TalismanCompleted");
			else
				if (last_day_of_the_week) then
					-- start proper hidden object game
					lev_num_completed = GetGameValue ("level_number")-1;
					episode = math.floor (lev_num_completed / 7);
					Print ("Episode number is "..episode.."\n");
					SwitchScreen ("HiddenWorld");--..episode);
					--SwitchScreen ("HiddenObjectCompleted");
				else
					SwitchScreen ("WorldMap");
				end;
			end;		
		end		
		return;
	end;
	
	
	if (name == "color") then
		SetProperty ("color:active", 0);
		color_akey = 0.001;
		starson = starsrequired;
		complete = 1;
	end;		

	if (name == "add") then
		Azkend_AddTalismanPart ();
	end;	
	

end;

function spawnAppearFx(name)

	x = GetProperty(name..":static_position.x");
	y = GetProperty(name..":static_position.y");
	width = GetProperty(name..":width");
	height = GetProperty(name..":height");
	step = 40
	
	for k = y, y+height, step do
		for i = x, x+width, step do
			--Print("pos: ".. i.."\n")
			SpawnFX ("fxs/bigstar.lua", i, k, 180, 0);	
		end;	
	end;
end;

function OnUpdate (tdelta)

	if (color_akey > 0) then
		color_akey = color_akey + tdelta;
	end;
	UpdateColoring ();


	if (timer < 0.5) then
		timer = timer+tdelta;
		
		if (timer >= 0.5) then
			x = GetProperty ("panel:aligned_position.x");
			y = GetProperty ("panel:aligned_position.y");
			SpawnFX ("fxs/panel-medium-outlines.lua", x, y, 0, 0)
		end;
	else
		timer = timer+tdelta;
	end;
	
	if (timer > 0.4) then
		if (talisman_parts < math.fmod (lev_num, 5)-1) then
			talisman_parts = talisman_parts + 1;
			Azkend_AddTalismanPart ();
			timer = 0;
		end;
	end;
	
	timer2 = timer2 + tdelta;
	
	Azkend_SetTalismanPos (GetProperty ("talisman:static_position.x"), GetProperty ("talisman:static_position.y"));

	Azkend_SetShamanPos (GetProperty ("shaman:static_position.x"), GetProperty ("shaman:static_position.y"));
	
	Azkend_UpdateTalisman (tdelta);
	--Azkend_UpdateShaman (tdelta);

	akey = GetActiveScreenAnimKey ();


	trans = math.sin (0.5*3.1415926535 * GetActiveScreenTransPhase ());
	SetProperty ("panel:position_offset.y", (1-trans) * 700 * -1 + color_offset);
	SetProperty ("panel:alpha", trans);
	SetProperty ("panel:scale", 0.6 + 0.4 * trans);

	SetProperty ("fader:alpha", trans + trans * 0.05 * math.sin (2*3.141592*akey));
	
	local perg_alpha = math.sin (math.pi/2 * math.min (1, math.max (0, timer-1)));
	SetProperty ("pergament1:alpha", perg_alpha*trans);
	SetProperty ("pergament1:position_offset.y", 20*(1-perg_alpha*trans));
	
	
	SetProperty ("star2:angle", math.sin(timer));
    SetProperty ("star2:alpha", GetActiveScreenTransPhase()*0.8);
    
    
    
    if(timer2 > 1.5 and interval1 > 0.05 and complete == 0) then
    	
    	
    	rank = math.floor(starson*5)-1;
     	if(rank < 0) then
     		rank = 0;
     	end;
     	
    	--Print("R: "..rank.."\n");
    	val = DM_GetValue ("xml/ranks.xml", "ranks", rank, "rank");
   		SetProperty ("rank:label.text", string.format (T_RANK, val));
   		
    	SetProperty ("timeslider:slider.value",starson);
    	
 		local time_left = string.format("%u", 100 * rankvalue * (starson/starsrequired));
 		SetProperty ("time_left:label.text", string.format(T_TIME_LEFT, time_left));
 		
    	PlaySound("ui/sfx/button-over.ogg");
    
		--Print("Rank now "..starson.."\n");
    	if(starson >= 1.0 and starlit == 0) then    		 		
    		PlaySound("music/trophy.ogg");
    		spawnAppearFx("rankstar0");
    		SetProperty("rankstar0:label.bitmap", "ui/gfx/starbig-on.png");
    		starlit = 1;
    	end;
    	
    	if(starson > starsrequired) then
    		complete = 1;
    	end;
    	
    	interval1 = 0;
    	starson = starson + 0.04;
    else
    	interval1 = interval1+tdelta;
    end;
   

end;


function OnDraw ()
	
	if (color_akey < 1) then
		Azkend_DrawTalisman ();
	else
		
	end;
	--Azkend_DrawShaman ();

end;
