
---- Highscore managment (data saved in highscores.data) ----
-------------------------------------------------------------------------------

Highscores = {
	data = { },
	diffShowing = 1
}

function Highscores:load()
	dofile("highscores.data")
	self.data = HighscoresData
end

function Highscores:isHighscore(score)
	return self:getPlace(score) <= 5
end

function Highscores:getPlace(score)
	for k,v in pairs(self.data[Difficulty.name]) do
		if v[2] < score then return k end
	end
	return 6
end

function Highscores:add(score, level)
	if self:isHighscore(score) then
		table.insert(self.data[Difficulty.name], self:getPlace(score), {playername, score, level})
		table.remove(self.data[Difficulty.name])
		self:save()
	end
end

function Highscores:get(diff, num)
	return self.data[Difficulties[diff].name][num]
end 

function Highscores:save()
	local f = assert(io.open("highscores.data", "w"))
	f:write("\nHighscoresData = ")
	serialize(self.data, f)
	f:write(string.format("\n\nplayername = %q\n", playername))
	io.close(f)
end

function Highscores:show()
	Window:show(160, nil, self:generateWindowFgFunc(), 
		function()
			ctrl = Controls.read()
			if ctrl:circle() or ctrl:cross() then Window:close() end
			if ctrl:r() then 
				self.diffShowing = math.mod(self.diffShowing, 4) + 1
				System.sleep(200)
			elseif ctrl:l() then
				self.diffShowing = self.diffShowing -1
				if self.diffShowing == 0 then self.diffShowing = 4 end
				System.sleep(200)
			end
		end)
end

function Highscores:generateWindowFgFunc()
	local i, sinf = 0, 0
	local x, sy = SCREEN_WIDTH2-124, 96
	local c, form = nil, string.format
	return function() 
		i, sinf = i+1, math.sin(i/6)
		c = Color.new(255,255,255,i*8)
		Crystal:print(Difficulties[self.diffShowing].name.." Highscores", SCREEN_WIDTH2, 64, Font.CENTER, c)
		Vera:print("Place    Name    Level    Score", x, sy, Font.LEFT, c)
		for j = 0, 4 do
			local hs = self:get(self.diffShowing, j+1)
			if j == 0 then c = Color.new(210+sinf*45,210+sinf*45, 50, i*8)
			elseif j == 1 then c = Color.new(255-sinf*60, 255-sinf*60, 255-sinf*60, i*8)
			else c = colors.verylightgray end
			Vera:print(form("%d %13s %4d %10d", j+1, hs[1], hs[3], hs[2]), x, sy+16+12*j, Font.LEFT, c)
		end
		
		Vera:print("L and R to show other difficulties,\n close with Cross or Circle.", SCREEN_WIDTH2, 188, Font.CENTER, Color.new(200,200,200,i*8))
	end
end
