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


local function on_load(itemstack, user)
    minetest.sound_play(("aom_muskets_pistol_cocked"), {
        gain = 0.15,
        pos = user:get_pos(),
        object = user,
        pitch = (math.random()*0.1) + 0.90
    })
end

local function use_musket(itemstack, user, pointed_thing)
    if not user:is_player() then return itemstack end
    local ret = aom_util.try_rightclick(itemstack, user, pointed_thing, false)
    if ret then
        return ret
    end

    aom_muskets.start_reload(user)

    if itemstack:get_wear() > 0 then
        minetest.sound_play(("aom_muskets_pistol_empty"), {
            gain = 1.5,
            pos = user:get_pos(),
            object = user,
            max_hear_distance = 100,
            pitch = (math.random()*0.1) + 0.90
        })
        return itemstack
    end

    itemstack:set_name("aom_muskets:pistol")
    itemstack:set_wear(65536 - 1)

    local dir = user:get_look_dir()
    if true then
        local d = 0.04
        dir = vector.offset(dir, (math.random()*d)-(d/2), (math.random()*d)-(d/2), (math.random()*d)-(d/2))
    end
    local pos = user:get_pos()

    pos = aom_muskets.get_eyepos(user)
    -- pos = vector.add(pos, dir)
    local yawoffset = minetest.yaw_to_dir(user:get_look_horizontal() - 1)
    yawoffset = vector.multiply(yawoffset, 0.2)
    local bullet_pos = pos --vector.add(pos, yawoffset)
    local ent = minetest.add_entity(bullet_pos, "aom_muskets:musket_shot_ENTITY"):get_luaentity()
    ent._shooter = user
    ent._damage = {pierce = 12, projectile = 1}
    ent._dir = dir
    ent._bullet_drop = -17
    ent._lifetime = 1
    -- ent._last_pos = pos
    minetest.sound_play(("aom_muskets_pistol"), {
        gain = 1.5,
        pos = bullet_pos,
        object = user,
        max_hear_distance = 100,
        pitch = (math.random()*0.1) + 0.90
    })

    local particle_pos = vector.add(pos, vector.multiply(dir, 0.9))
    particle_pos = vector.add(particle_pos, yawoffset)
    aom_muskets.do_smoke_particles(particle_pos, 20, dir, 6, 0.1)
    aom_muskets.do_particles(particle_pos, 10)
    local flashnode = minetest.get_node(bullet_pos)
    if flashnode.name == "air" then
        minetest.set_node(bullet_pos, {name="aom_util:light_node_14"})
        minetest.get_node_timer(bullet_pos):set(1,0.8)
    end
    return itemstack
end

minetest.register_tool("aom_muskets:pistol", {
    description = S("Pistol"),
    _tt_color = 3,
    _tt_long_desc = S("Flintlock pistol. Somewhat fast to reload and reasonably accurate."),
    _tt_how_to_use = S("Fire: [place node]").."\n"..S("Reload: 2-4s"),
    _tt_uses = "Infinite",
    inventory_image = "aom_muskets_pistol_loaded.png",
    wield_image = "aom_muskets_pistol.png^[transform3",
    wield_scale = {x=8.0/3,y=5.0/3,z=4.0},
    tool_capabilities = {
        damage_groups = {
            blunt=2,
        },
    },
    groups = { musket = 1 },
    on_secondary_use = use_musket,
    on_place = use_musket,
    _wield3d_textures = "aom_muskets:pistol_loaded",
    _wield3d_rotation =   {x=-90, y=0, z=-90},
    _wield3d_offset =   {x=0, y=2.0, z=1.0},
    _wield3d_scale = {x=0.12, y=0.12, z=0.12},
    _override_item_entity = {
        visual_size = {x=0.12, y=0.12, z=0.12},
    },
})
local on_fire = function(itemstack, player)
    local ct = player_info.get(player)
    if ct and not ct.ctrl.sneak then
        return use_musket(itemstack, player)
    end
end
minetest.register_tool("aom_muskets:pistol_loaded", {
    description = S("Pistol"),
    _tt_color = 3,
    _tt_long_desc = S("Flintlock pistol. Somewhat fast to reload and reasonably accurate."),
    _tt_how_to_use = S("Fire: [place node]").."\n"..S("Reload: 2-4s"),
    _tt_uses = "Infinite",
    inventory_image = "aom_muskets_pistol.png",
    wield_image = "[combine:24x24:0,0=aom_muskets_pistol.png",
    wield_scale = {x=3.0,y=2,z=3.0},
    tool_capabilities = {
        damage_groups = {
            blunt=2,
        },
    },
    groups = { musket = 1 },
    -- on_use = use_musket,
    on_secondary_use = on_fire,
    on_place = on_fire,
    _wield3d_offset =   {x=-0.7, y=4.5, z=-1.0},
    _wield3d_rotation =   {x=-90, y=30, z=-90},
    _wield3d_scale = {x=0.2, y=0.2, z=0.2},
    _override_item_entity = {
        visual_size = {x=0.2, y=0.2, z=0.2},
    },
})

if aom_vars.technology_level >= 4 then
    aom_tcraft.register_group_craft({
        output = "aom_muskets:pistol_loaded",
        items = {
            ["aom_muskets:flintlock_mechanism"] = 1,
            ["aom_items:iron_bar"] = 3,
        },
        group = "planks",
        group_count = 1
    })
    minetest.register_craft({
        output = "aom_muskets:pistol_loaded",
        recipe = {
        {"aom_muskets:pistol_loaded"},
        },
    })
end

aom_muskets.register_musket_reloader({
    name = "aom_muskets:pistol",
    time = 3,
    loaded = "aom_muskets:pistol_loaded",
    on_load = on_load,
    on_step = nil,
    require_wield = true,
    sneak_boost = 1,
    sprint_boost = 1,
    auto_reload = true,
})

aom_util.register_on_wield({
    name = "aom_muskets:pistol_loaded",
    on_change_to_item = function(player)
        aom_util.unset_fov(player, "aom_muskets:pistol_zoom")
        aom_muskets.start_reload(player)
        player_model.set_anim(player, {tag="aom_muskets_aim", actions={"aim"}})
    end,
    on_change_from_item = function(player)
        aom_util.unset_fov(player, "aom_muskets:pistol_zoom")
        player_model.unset_anim(player, "aom_muskets_aim")
    end,
    on_step = function(player, dtime)
        local ct = player_info.get(player)
        if ct and ct.ctrl.sneak and ct.ctrl.place then
            aom_util.set_fov(player, {
                tag = "aom_muskets:pistol_zoom",
                fov = 0.7,
                is_multiplier = true,
                transition_time = 0.2 })
        elseif aom_util.has_fov(player, "aom_muskets:pistol_zoom") ~= nil then
            aom_util.unset_fov(player, "aom_muskets:pistol_zoom")
        end
        if ct and ct.just_released.place and ct.ctrl.sneak then
            player:set_wielded_item(use_musket(player:get_wielded_item(), player))
        end
    end,
})
