-- LUALOCALS < ---------------------------------------------------------
local SecureRandom, io, klots, minetest, type
    = SecureRandom, io, klots, minetest, type
local io_open
    = io.open
-- LUALOCALS > ---------------------------------------------------------

do
	local worldpath = minetest.get_worldpath()
	local handle = io_open(worldpath .. "/klots_edit")
	if handle then
		klots.editmode = true
		handle:close()
	end
end

local formid = "klots_show_editor"

local tokenrand = SecureRandom()

local editor_callbacks = {}

function klots.show_editor(player, pos, text, callback)
	local pname = type(player) == "string" and player or player:get_player_name()
	local key = minetest.sha1(minetest.pos_to_string(pos, 0) .. pname)
	local token = minetest.sha1(tokenrand:next_bytes(16))
	editor_callbacks[key] = {
		callback = callback,
		token = token
	}
	minetest.show_formspec(pname, formid, "size[8,4,true]"
		.. "field[0,0;0,0;key;;" .. key .. "]"
		.. "field[0,0;0,0;token;;" .. token .. "]"
		.. "textarea[0.3,0;8,4;text;;"
		.. minetest.formspec_escape(text)
		.. "]button_exit[0,3.25;8,1;ok;Save]")
end

minetest.register_on_player_receive_fields(function(_, formname, fields)
		if formname ~= formid then return end
		if not (fields.key and fields.token and fields.text) then return end
		local cbdata = editor_callbacks[fields.key]
		if not (cbdata and cbdata.token == fields.token) then return end
		cbdata.callback(fields.text)
	end)
