local S = core.get_translator("cow_results")

cow_results = {}

-- Returns formspec string for allow_close.
local allow_close = function(player)
	if core.is_creative_enabled(player:get_player_name()) then
		-- We allow closing formspec in creative formspec for convenience
		return "allow_close[true]"
	else
		return "allow_close[false]"
	end
end

function cow_results.show_results(player, data)
	local score_img, score_size = cow_gui.render_integer(data.score)
	local score_w = score_size.x / score_size.y

	local score_h = 0.7
	score_w = score_w * score_h

	local highscore = data.highscore

	local highscore_img, highscore_size = cow_gui.render_integer(highscore)
	local highscore_w = highscore_size.x / highscore_size.y

	local highscore_h = score_h
	highscore_w = highscore_w * highscore_h

	local highscore_text_coords = "0.55,5.0;"..(4.547*highscore_h)..","..highscore_h
	local highscore_text_image
	if data.new_highscore == true then
		highscore_text_image = "animated_image["..highscore_text_coords..";highscore_text;cow_results_highscore_flashing.png;2;500;1;]"
	else
		highscore_text_image = "image["..highscore_text_coords..";cow_results_highscore.png]"
	end

	local form = "formspec_version[9]" ..
		"size[8.1,8.5]"..
		allow_close(player)..
		"set_focus[back;false]"..
		"style[back;fgimg_hovered=cow_menu_back_hover.png;fgimg_pressed=cow_menu_back_pressed.png]"..
		"box[0.35,3;7.45,"..(score_h*5.35)..";#1e7453ff]"..

		-- Score
		"image[0.55,3.2;"..(3.375*score_h)..","..score_h..";cow_results_score.png]"..
		"image[0.7,"..(3.4+score_h)..";"..score_w..","..score_h..";"..core.formspec_escape(score_img).."]"..

		-- Highscore
		highscore_text_image..
		"image[0.7,"..(5.2+highscore_h)..";"..highscore_w..","..highscore_h..";"..core.formspec_escape(highscore_img).."]"..

		"image[1,0.5;6,1.50512;cow_results_results.png]"..
		"image_button[0.5,7.3;2,0.75389;cow_menu_back.png;back;]"

	core.show_formspec(player:get_player_name(), "cow_results:results", form)
end

core.register_on_player_receive_fields(function(player, formname, fields)
	if formname == "cow_results:results" then
		if fields.back then
			cow_menu.open_menu(player, true)
		end
	end
end)


