local S = minetest.get_translator("lzr_speech")
local F = minetest.formspec_escape
local FS = function(...) return F(S(...)) end
local NS = function(s) return s end

local mod_credits = minetest.get_modpath("lzr_credits")

lzr_speech = {}

local speakers = {}

lzr_speech.register_speaker = function(id, name, portrait, sound)
	local speaker = { name = name, portrait = portrait, sound = sound }
	speakers[id] = speaker
end

lzr_speech.speak = function(player, message, speaker_id, portrait_override, sound_pitch, answer_type)
	if not speakers[speaker_id] then
		minetest.log("error", "[lzr_speech] Tried to call speak for non-existant speaker: "..tostring(speaker_id))
		return
	end
	local portrait
	if portrait_override then
		portrait = portrait_override
	else
		portrait = speakers[speaker_id].portrait
	end
	--~ @1 is a name
	local title = FS("@1 says:", speakers[speaker_id].name)
	local answers = ""
	if answer_type == "credits" then
		if mod_credits then
			answers = answers .. "button_exit[2.5,4.4;5,0.8;credits;"..FS("Show credits").."]"
		else
			answers = answers .. "button_exit[3.5,4.4;3,0.8;ok;"..FS("OK").."]"
		end
	else
		answers = "button_exit[3.5,4.4;3,0.8;ok;"..FS("OK").."]"
	end
	local form = "formspec_version[7]size[10,5.5]"..
		"box[0,0;10,0.8;#0000004f]"..
		"label[0.4,0.4;"..title.."]"..
		"box[0.5,1;2.0,3;#0000002f]"..
		"image[0.75,1;1.5,3;"..portrait.."]"..
		"box[3,1;6.5,3;#ffffff1f]"..
		"textarea[3,1;6.5,3;;;"..F(message).."]"..
		answers
	minetest.show_formspec(player:get_player_name(), "lzr_speech:speech", form)

	if speakers[speaker_id].sound then
		minetest.sound_play({name=speakers[speaker_id].sound}, {to_player=player:get_player_name(), pitch=sound_pitch})
	end
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
	if formname ~= "lzr_speech:speech" then
		return
	end
	if fields.credits and mod_credits then
		minetest.log("action", "[lzr_speech] "..player:get_player_name().." wants to see the credits")
		lzr_credits.show_credits(player)
	end
end)
