require("lualibs.common")
require("skilanderkit")
boardname="menu.map"

curtime = 0


function init(newinitpos, hotload)
	initpos = table_shallow_copy(newinitpos)

	allvis = 10

	for i = 0,numsectors()-1
	do
		sector_visibility(i, allvis)
		--print(i, sector_visibility(i))
	end

	loadsong("music/charts.kdm")
	setmusic(true)

	load_altpal(1, "grayhack")


	--g_wintimer = 100
	--g_winmap = 4
	--g_winstuff = 53.5
	curtime = 0

end

-- Key Settings
--  Here's a map of all the keyboard scan codes: NOTE: values are listed in hex!
-- +---------------------------------------------------------------------------------------------+
-- | 01   3B  3C  3D  3E   3F  40  41  42   43  44  57  58          46                           |
-- |ESC   F1  F2  F3  F4   F5  F6  F7  F8   F9 F10 F11 F12        SCROLL                         |
-- |                                                                                             |
-- |29  02  03  04  05  06  07  08  09  0A  0B  0C  0D   0E     D2  C7  C9      45  B5  37  4A   |
-- | ` '1' '2' '3' '4' '5' '6' '7' '8' '9' '0'  -   =  BACK    INS HOME PGUP  NUMLK KP/ KP* KP-  |
-- |                                                                                             |
-- | 0F  10  11  12  13  14  15  16  17  18  19  1A  1B  2B     D3  CF  D1      47  48  49  4E   |
-- |TAB  Q   W   E   R   T   Y   U   I   O   P   [   ]    \    DEL END PGDN    KP7 KP8 KP9 KP+   |
-- |                                                                                             |
-- | 3A   1E  1F  20  21  22  23  24  25  26  27  28     1C                     4B  4C  4D       |
-- |CAPS  A   S   D   F   G   H   J   K   L   ;   '   ENTER                    KP4 KP5 KP6    9C |
-- |                                                                                      KPENTER|
-- |  2A    2C  2D  2E  2F  30  31  32  33  34  35    36            C8          4F  50  51       |
-- |LSHIFT  Z   X   C   V   B   N   M   ,   .   /   RSHIFT          UP         KP1 KP2 KP3       |
-- |                                                                                             |
-- | 1D     38              39                  B8     9D       CB  D0   CD      52    53        |
-- |LCTRL  LALT           SPACE                RALT   RCTRL   LEFT DOWN RIGHT    KP0    KP.      |
-- +---------------------------------------------------------------------------------------------+

allkeys =
{
{ 0x02, "1", true },
{ 0x03, "2", true },
{ 0x04, "3", true },
{ 0x05, "4", true },
{ 0x06, "5", true },
{ 0x07, "6", true },
{ 0x08, "7", true },
{ 0x09, "8", true },
{ 0x0A, "9", true },
{ 0x0B, "0", true },
{ 0x10, "Q", true },
{ 0x11, "W", true },
{ 0x12, "E", true },
{ 0x13, "R", true },
{ 0x14, "T", true },
{ 0x15, "Y", true },
{ 0x16, "U", true },
{ 0x17, "I", true },
{ 0x18, "O", true },
{ 0x19, "P", true },
{ 0x1E, "A", true },
{ 0x1F, "S", true },
{ 0x20, "D", true },
{ 0x21, "F", true },
{ 0x22, "G", true },
{ 0x23, "H", true },
{ 0x24, "J", true },
{ 0x25, "K", true },
{ 0x26, "L", true },
{ 0x2C, "Z", true },
{ 0x2D, "X", true },
{ 0x2E, "C", true },
{ 0x2F, "V", true },
{ 0x30, "B", true },
{ 0x31, "N", true },
{ 0x32, "M", true },
{ 0x39, " ", true },
{ 0x33, ",", true },
{ 0x34, ".", true },
{ 0x0E, 0,   true },
{ 0xCB, 1,   true },
{ 0xCD, 2,   true },
}


g_winmap = 1
curentry = 0

playernamepos = 1

hiscores_file = loadfile("highscore.lua")
--print("hiscroes",hiscores_file)
if (hiscores_file) then
	hiscores_file()
else
	dofile("inithighscore.lua")
end

function truncatescore()
	for mi, mv in ipairs(hiscores) do
		for ei, ev in ipairs(mv) do
			if (ei > 10) then
				mv[ei] = nil
			end
		end
	end
end

truncatescore()

function savescore()
	file = io.open("highscore.lua", "w")
	file:write("hiscores = {")
	for mi, mv in ipairs(hiscores) do
		file:write("{")
		for ei, ev in ipairs(mv) do
			file:write(string.format("{%f,%f,\"%s\"},", ev[1],ev[2],ev[3]))

		end
		file:write("},")
	end
	file:write("}")
	
	file:close()
end

function frame()
	curtime = curtime + 1.0
	cc = 3.0 + math.sin(curtime * 0.1)*2.0
	--clearview(3*32+math.floor(cc))


	b_visibility(2000)

	local mypos = table_shallow_copy(initpos)
	mypos.z = mypos.z + math.sin(curtime * 0.0312) * 16.0 - 1000
	drawrooms(mypos.x, mypos.y, mypos.z, mypos.ang, 50, mypos.sect)

	drawmasks()

	drawtext("TOP SKIMASTERS", 70, 10, 1.0, 0, 15.0)

	if (g_wintimer) then
		local sec,csec = math.modf(g_wintimer)
		drawtimer(string.format("CONGRATS YOU WON %02d:%02d", sec, math.floor(csec*100)), 50, 100, 0.7, 0)
		if (curtime > 50) then
			table.insert(hiscores[g_winmap], { g_wintimer, g_winstuff, "New" })
			
			if (g_winmap == 5) then -- nag screen
				table.sort(hiscores[g_winmap], function(x, y) return x[1] > y[1] end)
			else
				table.sort(hiscores[g_winmap], function(x, y) return x[1] < y[1] end)
			end

			print(dump(hiscores[g_winmap]))
			truncatescore()

			curentry = 0
			for i,v in ipairs(hiscores[g_winmap]) do
				if (v[3] == "New") then
					curentry = i
					playernamepos = 1
					v[3] = "   "
				end
			end


			g_wintimer = nil
		end
	else

		if (curentry > 0) then
			--print("current entry", curentry)
			--hiscores[g_winmap][curentry][3] = "ASS"


			for i, v in ipairs(allkeys) do
				local stat = getkeystatus(v[1])
				-- and type(v2) == "number"
				if ( not v[3] and stat and v[2] == 0 ) then
					hiscores[g_winmap][curentry][3] = replace_char( playernamepos, hiscores[g_winmap][curentry][3], " " )
					playernamepos = math.max(1, playernamepos - 1)
				elseif ( not v[3] and stat and v[2] == 1 ) then
					playernamepos = math.max(1, playernamepos - 1)
				elseif ( not v[3] and stat and v[2] == 2 ) then
					playernamepos = math.min(3, playernamepos + 1)

				elseif ( not v[3] and stat ) then
					--print(dump(v))
					--drawtext(v[2], 160, 70, 1.0, 0, 15.0)
					--hiscores[g_winmap][curentry][3][playernamepos] = v[2]
					print( hiscores[g_winmap][curentry][3] )
					hiscores[g_winmap][curentry][3] = replace_char( playernamepos, hiscores[g_winmap][curentry][3], v[2] )
					print("key",v[2])
					playernamepos = math.min(3, playernamepos + 1)
				end
		
				v[3] = stat
			end

			if (getkeystatus(1) or getkeystatus(0x1c)) then
				curentry = 0
				lastkey = true
			end

		else
			local anykey = getkeystatus(1) or getkeystatus(0x1c) or getkeystatus(0xCB) or getkeystatus(0xCD)

			if (getkeystatus(1) or getkeystatus(0x1c) and not gotomode and not lastkey) then
				gotomode = 0
				gomode = nil -- ehkä vois poistaa

				g_wintimer = nil

				savescore()
				lastkey = true
			elseif (getkeystatus(0xCB) and not lastkey) then
				g_winmap = ( (g_winmap - 1 + 5 - 1) % 5 ) + 1
				lastkey = true
			elseif (getkeystatus(0xCD) and not lastkey) then
				g_winmap = ( (g_winmap - 1 + 5 + 1) % 5 ) + 1
				lastkey = true
			elseif not anykey then
				lastkey = false
			end



		end


		--print(dump(hiscores))
		--print("-----------")

		mapnames = {
			"TUTORIAL",
			"SKI'ERS LANDING",
			"SANDSTROEMMING",
			"MRR SLOPE",
			"NAG SCREEN",
		}

		drawtext(string.format("HI-SCORE FOR MAP %d", g_winmap), 30, 50, 0.8, 15, 19.0, 1)
		drawtext(string.format("%s", mapnames[g_winmap]), 90, 65, 0.8, 0, 19.0, 1)

		if (curentry > 0) then
			cursorx = 70 + 15.0*0.4 * (playernamepos + 0)
			cursory = 70 + curentry * 10.0

			rotatesprite(cursorx, cursory, 0.1, curtime,   200, 0,0, 3,    0,0,1,1);
		end


		for i,v in ipairs(hiscores[g_winmap]) do
			local ev = v[1]
			if (ev > 999.99) then
				ev = 999.99
			end
			local sec,csec = math.modf(ev)
			prettytime = string.format("%03d:%02d", sec, math.floor(csec*100))
			if (prettytime:sub(1,1) == "0") then
				prettytime = replace_char( 1, prettytime, " ")
			end

			local shad = 8
			if (i == curentry) then
				shad = 4+math.sin(curtime * 0.132) * 4.0
			end
			if (curentry == 0) then
				shad = 0
			end

			drawtext(string.format("%2d. %s - %s - %3.f PER CENT STUFF", i, v[3], prettytime, v[2]), 50, 70 + i * 10.0, 0.4, shad, 15.0)
			--print(dump(v))
		end


	end


end
