---------------------------
-- Copyright 2008, Don Reba
---------------------------

class "fb2k_link"

-- Main function.
function run()
	local time = time_global()

	if fb2k_link.polling_delay == nil then
		fb2k_link.polling_delay = 2000
	end

	if fb2k_link.time == nil or fb2k_link.time + fb2k_link.polling_delay < time then
		display_log()
		fb2k_link.time = time
	end
end


-- Displays the events contained in "config\fb2k.ltx".
-- The file is organized as a circular buffer.
function display_log()
	local ltx = ini_file("fb2k.ltx")
	if not ltx then
		return
	end

	if not ltx:line_exist("info", "format_version") or 1 ~= ltx:r_u32("info", "format_version") then
		return
	end

	fb2k_link.polling_delay = ltx:r_u32("info",  "polling_delay")
	fb2k_link.suspend_input = ltx:r_bool("info", "suspend_input")

	local event_count = ltx:r_u32("info", "event_count")
	local last_slot   = ltx:r_u32("info", "last_slot")

	if fb2k_link.slot == nil then
		fb2k_link.slot = 0
	end

	if (last_slot + 1) % event_count == fb2k_link.slot then
		return
	end

	local head = fb2k_link.slot
	local tail = last_slot

	fb2k_link.slot = (last_slot + 1) % event_count

	if head <= tail then
		for slot = head, tail, 1 do
			process_event(ltx, slot)
		end
	else
		for slot = head, event_count - 1, 1 do
			process_event(ltx, slot)
		end
		for slot = 0, tail, 1 do
			process_event(ltx, slot)
		end
	end
end

-- Displays a single event from the given ini file.
function process_event(ltx, slot)
	local slot_name = "event@" .. slot
	local event_text = ltx:r_string_wq (slot_name, "text")
	local event_type = ltx:r_string    (slot_name, "type")


	local icon_x
	local icon_y
	if     event_type == "init"          then icon_x, icon_y = 0, 0
	elseif event_type == "control_on"    then icon_x, icon_y = 1, 0
	elseif event_type == "control_off"   then icon_x, icon_y = 1, 0
	elseif event_type == "info"          then icon_x, icon_y = 1, 0
	elseif event_type == "stop"          then icon_x, icon_y = 1, 1
	elseif event_type == "seek"          then icon_x, icon_y = 0, 1
	elseif event_type == "pause"         then icon_x, icon_y = 0, 2
	elseif event_type == "track_change"  then icon_x, icon_y = 1, 2
	elseif event_type == "volume_change" then icon_x, icon_y = 0, 3
	elseif event_type == "volume_mute"   then icon_x, icon_y = 1, 3
	else   return
	end

	local text      = "Foobar2000\\n" .. event_text
	local texture   = "ui\\ui_icons_fb2k"
	local rect      = Frect():set(icon_x * 56, icon_y * 36, 56, 36)
	local timeout   = 0
	local show_time = 5000
	db.actor:give_game_news(text, texture, rect, timeout, show_time)

	if fb2k_link.suspend_input then
		if     event_type == "control_on"  then level.disable_input()
		elseif event_type == "control_off" then level.enable_input()
		end
	end
end
