require "UserData/Maps/LuaExamples/jutility" -- Contains tileString() function.

local tagPlayerButton   = 1
local tagPrevMap        = 1001
local tagNextMap        = 1002

local lastRoundTime -- For checking when a new second has started.

--[[
Prints a string with tiles (in layer 1), starting at tile x,y, padding to maxLength with empty spaces (0,0 in tileset).
local function tileString(str, x, y, maxLength)
	local ascii
	local tx
	local ty
	for i=1, maxLength do
		ascii = string.byte(str, i)
		if ascii == nil then
			tx = 0
			ty = 0
		else
			tx = ascii % 16
			ty = ascii / 16
		end
		kfyMap:tileSetTilesetCoordsAt(x+i-1, y, 1, tx, ty)
	end
end
--]]

-- Functions called by KFY:

function mapOnRoundBegin()
	displayMapName()
	lastRoundTime = -1
end

function mapOnUpdate()
	local roundTime = math.floor(kfyRound:getTime())
	if lastRoundTime == -1 or lastRoundTime ~= roundTime then -- Only change tiles on start of new full second.
		tileString(kfyRound:getTimeHoursMinsSecs(), 14, 58, 8)
		lastRoundTime = roundTime
	end
end

function mapOnTileLmbClick(tag, x, y, player)
	-- Next / Previous map buttons:
	if tag == tagPrevMap then
		kfyRound:prevMap(true)
	elseif tag == tagNextMap then
		kfyRound:nextMap(true)

	-- Player info button:
	elseif tag == tagPlayerButton then
		local kdStr = player:getKills().."/"..player:getDeaths()
		local pos = player:getCenterPosition()
		local posStr = math.floor(pos.x)..","..math.floor(pos.y)
		local vel = player:getVelocity()
		local velStr = math.floor(vel.x)..","..math.floor(vel.y)
		local mouseStr = player:getMouseX()..","..player:getMouseY();
		tileString(player:getName(), 37, 51, 16)
		tileString(player:getWinMsg(), 37, 52, 20)
		tileString(player:getHealth(), 37, 53, 4)
		tileString(player:getSauce(), 37, 54, 4)
		tileString(kdStr, 37, 55, 5)
		tileString(posStr, 37, 56, 7)
		tileString(velStr, 37, 57, 7)
		tileString(mouseStr, 37, 58, 7)
	end
end
