local mod_name = core.get_current_modname()
local mod_path = core.get_modpath(mod_name)
local S = core.get_translator(mod_name)


aom_rope.coil = {}
aom_rope.coil.speed = 20
aom_rope.coil.gravity = 4


function aom_rope.coil.throw(pos, direction)
    pos = vector.offset(pos, 0, 1.7, 0)
    local object = core.add_entity(pos, "aom_rope:rope_coil_ENTITY")
    local self = object:get_luaentity()
    object:set_velocity(vector.multiply(direction, aom_rope.coil.speed))
end

-- #TODO this should just call an appropriate function in the rope.lua instead of 
-- implementing its own placement function
function aom_rope.coil.uncoil(self, pos)
    local itemstack = ItemStack(self._itemstack)

    local collide_node = core.get_node(pos)
    local below_node = core.get_node(vector.offset(pos, 0, -1, 0))
    if aom_util.has_adjacent(pos, "solid") == 0
    or (not (core.registered_nodes[below_node.name] or {}).buildable_to
    and core.get_item_group(below_node.name, "rope") == 0) then
        core.add_item(pos, itemstack)
        -- core.log("rope coil hit the floor")
        return ItemStack()
    end

    -- the offset for the loop
    local i = 0
    local above_node = core.get_node(vector.offset(pos, 0, 1, 0))
    if not (core.registered_nodes[above_node.name] or {}).walkable
    and core.get_item_group(above_node.name, "rope") == 0
    and collide_node.name ~= "aom_rope:rope" then
        core.set_node(pos, {name="aom_rope:rope_anchor"})
        -- set the offset so it doesn"t dig the anchor
        i = 1
    end

    while (itemstack:get_count() > 0) and i < 200 do
        local p = vector.offset(pos, 0, -i, 0)
        local placenode = core.get_node(p)
        local def = core.registered_nodes[placenode.name]
        if def.walkable then
            core.add_item(vector.offset(p, 0, 1.2, 0), itemstack)
            return ItemStack()
        elseif placenode.name == "air"
        or def.buildable_to then
            core.dig_node(p)
            core.set_node(p, {name=itemstack:get_name()})
            itemstack:take_item()
        elseif placenode.name == "aom_rope:rope_anchor" then
            core.set_node(p, {name=itemstack:get_name()})
            itemstack:take_item()
        end
        i = i + 1
    end
end


-- entity
core.register_entity("aom_rope:rope_coil_ENTITY", {
    initial_properties = {
        physical = false,
        textures = {"aom_rope_coil.png"},
        visual_size = {x=0.5, y=0.5},
        collisionbox = {-0.1, -0.1, -0.1, 0.1, 0.1, 0.1,},
        pointable = false,
    },
    timer = 0,
    _last_pos = false,
    _itemstack = ItemStack({name="aom_rope:rope", count=8}),
    on_step = function(self, dtime, moveresult)
        local pos = self.object:get_pos()
        if self._last_pos == false then self._last_pos = pos return end
        local vel = self.object:get_velocity()
        vel = vector.multiply(vel, 0.99)
        vel.y = vel.y - aom_rope.coil.gravity * dtime
        self.object:set_velocity(vel)

        -- if not moveresult or not moveresult.collisions then return end
        -- make sure you collided
        local collided = false
        -- for _, collision in pairs(moveresult.collisions) do
        --   if collision.type == "node" then
        --     collided = true
        --     break
        --   end
        -- end
        if not collided
        and (core.registered_nodes[core.get_node(pos).name] or {}).walkable then
            collided = true
        end
        -- if collided and there"s a spot to put the rope, then do so
        if collided then
            if core.get_node(self._last_pos).name == "air"
            or (core.registered_nodes[core.get_node(self._last_pos).name] or {}).buildable_to
            or core.get_item_group(core.get_node(self._last_pos).name, "rope") ~= 0 then
                aom_rope.coil.uncoil(self, self._last_pos)
                self.object:remove()
            end
        end
        self._last_pos = pos
    end,
})


core.register_craftitem("aom_rope:rope_coil", {
    description = S("Rope Coil"),
    _tt_long_desc = S("Can be thrown at a wall or ceiling and will uncoil into rope you can climb on."),
    _tt_how_to_use = S("Use: [place]").."\n"..S("aim at walls and overhangs"),
    inventory_image = "aom_rope_coil.png",
    groups = { item_rope_coil = 1, craftitem = 1, item_burns = 1, tool = 1, rope_coil = 1, },
    on_secondary_use = function(itemstack, user, pointed_thing)
	    if not core.is_player(user) then return end
        local dir = user:get_look_dir()
        local pos = user:get_pos()
        local ctrl = core.is_player(user) and user:get_player_control()
        if ctrl and ctrl.sneak then return itemstack end
        itemstack:take_item()
        aom_rope.coil.throw(pos, dir)
        return itemstack
    end
})


if true then
    local r = "aom_rope:rope"
    core.register_craft({
        output = "aom_rope:rope_coil 1",
        recipe = {
            {r, r, r},
            {r,"", r},
            {r, r, r},
        }
    })
end
