local function furnace_formspec(pos)
  local spos = string.format("%d,%d,%d", pos.x, pos.y, pos.z)

  local formspec = {
    "size[8,9]",
    "list[nodemeta:", spos, ";main;0,0;8,4;]",
    "list[context;src;1,1;1,1;]",
    "list[context;fuel;1,2.5;1,1;]",
    "list[context;dst;5,1.25;2,2;]",
    "button[0,3.5;4,2;smelt;Smelt]",
    "button[4,3.5;4,2;smelt3;Smelt 3]",
    "list[current_player;main;0,5;8,4;]"
  }

  return table.concat(formspec)
end

PyuTest.make_node("pyutest_furnace:furnace", "Furnace", {
  cracky = PyuTest.BLOCK_NORMAL,
  level = 1
}, {
  "pyutest-furnace-top-bottom.png",
  "pyutest-furnace-top-bottom.png",
  "pyutest-furnace-sides.png",
  "pyutest-furnace-sides.png",
  "pyutest-furnace-sides.png",
  "pyutest-furnace-front.png",
}, {
  is_ground_content = false,
  paramtype2 = "facedir",
  on_construct = function(pos)
    local meta = core.get_meta(pos)
    local inventory = meta:get_inventory()
    inventory:set_size("src", 1)
    inventory:set_size("fuel", 1)
    inventory:set_size("dst", 4)
    meta:set_string("formspec", furnace_formspec(pos))
  end,
  on_destruct = function(pos)
    local drops = {}
    PyuTest.get_inventory_drops(pos, "src", drops)
    PyuTest.get_inventory_drops(pos, "fuel", drops)
    PyuTest.get_inventory_drops(pos, "dst", drops)

    for _, v in pairs(drops) do
      core.add_item(pos, v)
    end
  end,
  on_receive_fields = function(pos, formname, fields, player)
    if fields.quit then
      return
    end

    local meta = core.get_meta(pos)
    local inv = meta:get_inventory()

    local function smelt()
      local src = inv:get_stack("src", 1)
      local fuel = inv:get_stack("fuel", 1)

      if core.get_item_group(fuel:get_name(), "fuel") == 0 then
        return
      end

      local output, decremented_input = core.get_craft_result({
        method = "cooking",
        width = 1,
        items = {
          src
        }
      })


      if output.item:is_empty() then
        return
      end

      inv:add_item("dst", output.item)
      src:set_count(src:get_count() - output.item:get_count())
      fuel:set_count(fuel:get_count() - 1)
      inv:set_stack("src", 1, src)
      inv:set_stack("fuel", 1, fuel)
    end

    if fields.smelt then
      smelt()
    end

    if fields.smelt3 then
      for i = 1, 3 do
        smelt()
      end
    end
  end,
  _pyutest_blast_resistance = 3
})
