local box = {
   type = 'fixed',
   fixed = {-.4, -.5, -.4, .4, -.4, .4}, -- Right, Bottom, Back, Left, Top, Front
}

local function code_formspec_answer(pos)
   local meta = minetest.get_meta(pos)
   local num = math.random(800000,900000)
   meta:set_string('num', num)
   local formspec =
   'formspec_version[3]'..
   'size[12,8]'..
   'label[5,3;'..num..']'
   return formspec
end

local code_formspec_question =
   'formspec_version[3]'..
   'size[12,8]'..
   'field[3,2;6,1;number;Enter the number from the previous screen;]'..
   'button_exit[3,3;2,1;save;Submit]'

minetest.register_node('tasks:code_0', {
   description = 'code node',
   drawtype = 'mesh',
   param = 'light',
   paramtype2 = 'wallmounted',
   mesh = 'tasks_wall_panel.obj',
   tiles = {name='task_screen.png'},
   groups = {breakable=1, tasks=1},
   light_source = 14,
   selection_box = box,
   collision_box = box,
   on_construct = tasks.on_contruct,
   on_rightclick = tasks.right_click,
   on_timer = function(pos)
      local node = minetest.get_node(pos)
      minetest.swap_node(pos, {name = 'tasks:code_1', param2 = node.param2})
   end,
})

minetest.register_node('tasks:code_1', {
   description = 'code node',
   drawtype = 'mesh',
   param = 'light',
   paramtype2 = 'wallmounted',
   mesh = 'tasks_wall_panel.obj',
   tiles = {name='task_screen.png'},
   groups = {breakable=1, not_in_creative_inventory=1, tasks=1},
   light_source = 2,
   selection_box = box,
   collision_box = box,
   drop = 'tasks:code_0',
   on_rightclick = function(pos, node, clicker)
      local meta = minetest.get_meta(pos)
      meta:set_string('formspec', code_formspec_answer(pos))
      minetest.after(2, function()
         meta:set_string('formspec', code_formspec_question)
      end)
   end,
   on_receive_fields = function(pos, formname, fields, sender)
      if fields ['save'] then
         local meta = minetest.get_meta(pos)
         local answer = meta:get_string('num')
         if answer == fields.number then
            local node = minetest.get_node(pos)
            tasks.add_xp(pos, node, sender, 'tasks:code_0')
         else
            minetest.chat_send_player(sender:get_player_name(), 'Try again!')
         end
      end
   end,
})
