local formspec = "size[8,3]" ..
      "field[0.25,0.5;8,1;code;Execute;]" ..
      "button_exit[0,1;2,1;exit;Send]"

local function tablet_use(itemstack, placer, pointed_thing)
  local formy = formspec
  if placer:get_wielded_item():get_metadata() ~= nil and placer:get_wielded_item():get_metadata() ~= "" then
    formy = formspec .. "button_exit[2,1;2,1;last;Last]"
  end
  minetest.show_formspec(placer:get_player_name(), "sparkdebug:f_tablet",formy)
  return itemstack
end

minetest.register_tool("sparkdebug:tablet", {
  description = "Tablet",
  inventory_image = "tablet.png",
  stack_max = 1,
  on_place = tablet_use,
  on_secondary_use = tablet_use
})

-- Register callback
minetest.register_on_player_receive_fields(function(player, form, fields)
  if form ~= "sparkdebug:f_tablet" then
    return false
  end

  local item = player:get_wielded_item()
  if fields.last then
    fields.code = item:get_metadata()
  end

  if fields.code == nil or fields.code == "" then
    return true
  end

  item:set_metadata(fields.code)
  player:set_wielded_item(item)

  --[[local func = loadstring(fields.code)()
  local val = func.init()
  local ret = "No return value"
  if not (val == nil) then
    ret = val
  end]]--

  local suc, val = pcall(loadstring, fields.code)
  local ret = "E"
  local _ = ""
  if suc then
    _, ret = pcall(val, sparktech)
  else
    ret = val
  end
  if ret == nil then
    ret = "<nil>"
  end
	minetest.chat_send_player(player:get_player_name(), ret)
	return true
end)
