local MT = minetest
local vMod = vm_lighting_wand

-- returns a noderef only if its still registered (uninstalled mod)
local get_registered_node = function(pos)
  local node = MT.get_node_or_nil(pos)
  return MT.registered_nodes[node.name] ~= nil and MT.registered_nodes[node.name] or nil
end

local check_groups = function(groups)
  if groups == nil then
    return true
  end
  for group, _ in pairs(groups) do
    if vMod.is_ignored_group(group) ~= nil then
      return false
    end
  end
  return true
end

-- given a player will return where ever the crosshair is pointing upto range limit
vMod.get_pointed_node = function(player, objects, sneak, range)
  local result
  local eye_height = player:get_properties().eye_height or 1.625
  local eye_offset = player:get_eye_offset()
  local eye_pos = {
    x = eye_offset.x * 0.1,
    y = eye_height + eye_offset.y,
    z = eye_offset.z * 0.1
  }
  local pos = vector.add(player:get_pos(), eye_pos)
  local dir = player:get_look_dir()
  sneak = sneak and player:get_player_control().sneak or false
  objects = objects or false
  local ray = MT.raycast(pos, vector.add(pos, vector.multiply(dir, range)), objects, sneak)
  for pointed_thing in ray do
    local node_under = get_registered_node(pointed_thing.under)
    -- we found a node, check its not ignored
    if node_under ~= nil then
      if not vMod.is_ignored_drawtype(node_under.drawtype) and not vMod.is_ignored_name(node_under.name) then
        if check_groups(node_under.groups) then
          result = {
            pos_under = pointed_thing.under,
            pos_above = pointed_thing.above,
            node_under = node_under,
            node_above = get_registered_node(pointed_thing.above)
          }
          break
        end
      end
    else
      -- looks like we found a unknown node - uninstalled mod
      result = {
        pos_under = pointed_thing.under,
        pos_above = pointed_thing.above,
        node_under = nil,
        node_above = get_registered_node(pointed_thing.above)
      }
      break
    end
  end
  return result
end
