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

local sceptre_users = {}

local function max_orb_check(user)
    if sceptre_users[user] and #sceptre_users[user].orbs > 4 then
        local self = table.remove(sceptre_users[user].orbs, 1)
        self.object:remove()
    end
end

local function use_sceptre(itemstack, user, pointed_thing)
    local uses = minetest.registered_items[itemstack:get_name()]._uses
    if itemstack:get_wear() >= 65536 - 1 then return end
    if not user:is_player() then return itemstack end
    local dir = user:get_look_dir()
    local pos = user:get_pos()

    pos = vector.offset(pos, 0, 1.3, 0)
    pos = vector.add(pos, dir)
    local object = minetest.add_entity(pos, "aom_underworld:cortite_orb")
    minetest.sound_play(("aom_underworld_orb_whoosh"), {
        gain = 1.5,
        pos = object:get_pos(),
        object = object,
        pitch = (math.random()*0.2) + 0.9
    })
    object:set_velocity(vector.multiply(dir, 30))

    if not sceptre_users[user] then
        sceptre_users[user] = {orbs={}}
    end

    sceptre_users[user].orbs[#sceptre_users[user].orbs+1] = object:get_luaentity()
    max_orb_check(user)

    local wear = itemstack:get_wear()
    wear = math.min(wear + (65536/uses), 65535)
    itemstack:set_wear(wear)
    return itemstack
end

minetest.register_tool("aom_underworld:cortite_sceptre", {
    description = S("Cortite Sceptre"),
    _tt_color = 5,
    _tt_long_desc = S("Fires a glow light ahead to illuminate the darkness"),
    _tt_how_to_use = S("Use: [dig]"),
    _tt_uses = 128,
    _uses = 128,
    inventory_image = "aom_underworld_cortite_sceptre.png",
    groups = { sceptre = 1 },
    -- on_secondary_use = use_sceptre,
    on_use = use_sceptre,
})
if true then
    local r = "aom_underworld:cortite_rod"
    local m = "aom_underworld:mythril"
    local g = "aom_underworld:glow_rock"
    minetest.register_craft({
        output = "aom_underworld:cortite_sceptre",
        recipe = {
        {m, g, m},
        {"",r,""},
        {"",r,""},
        },
    })
    local s = "aom_underworld:cortite_sceptre"
    minetest.register_craft({
        output = "aom_underworld:cortite_sceptre",
        recipe = {
        {g,g,g},
        {g,s,g},
        {g,g,g},
        },
    })
end

local function do_particles(self, n)
    local pos = self.object:get_pos()
    local va = 0.5
    n = n or 10
    for i = 1, n do
        minetest.add_particle({
            pos = vector.offset(pos, (math.random() * va)-va/2, (math.random() * va)-va/2, (math.random() * va)-va/2),
            velocity = vector.new((math.random()-0.5)*5,(math.random()-0.5)*5,(math.random()-0.5)*5),
            expirationtime = math.random() * 0.5,
            size = math.random() * 3,
            collisiondetection = false,
            vertical = false,
            texture = "aom_underworld_cortite_sceptre_orb.png",
            glow = 14,
        })
    end
end


local tex = "aom_underworld_cortite_sceptre_orb.png"
minetest.register_entity("aom_underworld:cortite_orb", {
    initial_properties = {
        physical = false,
        textures = {tex, tex, tex, tex, tex, tex,},
        visual = "cube",
        visual_size = {x=0.5, y=0.5},
        collisionbox = {-0.2, -0.2, -0.2, 0.2, 0.2, 0.2,},
        use_texture_alpha = false,
        pointable = false,
        glow = 14,
        static_save = false,
    },
    _last_pos = false,
    _parent = nil,
    _timer = 0,
    on_step = function(self, dtime, moveresult)
        self._timer = self._timer + dtime
        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.98)
        self.object:set_velocity(vel)

        if math.random() < 0.1 or self._timer < 2 and math.random() < 0.5 then
            local va = 1
            minetest.add_particle({
                pos = vector.offset(pos, (math.random() * va)-va/2, (math.random() * va)-va/2, (math.random() * va)-va/2),
                velocity = vector.new((math.random()-0.5)*1,(math.random()-0.5)+0.5,(math.random()-0.5)*1),
                expirationtime = (math.random()*2)^2 + 0.4,
                size = math.random() * 1,
                collisiondetection = false,
                vertical = false,
                texture = "aom_underworld_cortite_sceptre_orb_particle.png",
                glow = 10,
            })
        end

        -- local fdir = vector.new(
        --     math.sin((0.7 * self._timer) % 6.28),
        --     math.cos((0.9 * self._timer) % 6.28),
        --     math.cos((1 * self._timer) % 6.28)
        -- )
        -- self.object:set_rotation(fdir)

        if not self._collided then
            if (minetest.registered_nodes[minetest.get_node(pos).name] or {}).walkable then
                self._collided = true
            elseif self._timer > 2 then
                self.object:set_velocity(vector.new())
                self._collided = true
            end
        end
        if self._timer > 10 and not self._removed then
            do_particles(self)
            self.object:remove()
            self._removed = true
            return false
        end
        if self._collided and not self._stopped then
            self.object:set_velocity(vector.new())
            self.object:set_pos(vector.add(pos, vector.multiply(vector.normalize(vel), -2)))
            self._stopped = true
        end
        self._last_pos = pos

        local node = minetest.get_node(pos)
        if node.name == "air" then
            minetest.set_node(pos, {name="aom_util:light_node_14"})
            minetest.get_node_timer(pos):start(1)
        elseif node.name == "aom_util:light_node_14" then
            minetest.get_node_timer(pos):set(1, 0.5)
        end
    end,
})
