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

local node_box
if true then
    local pw = 4/16 -- width
    local pl = 8/16 -- length
    local pa = 2/16 -- length
    node_box = {
        type = "fixed",
        fixed = {
            {-pl, -pl,  -pl,
              pl,  pl,  4/16},
            {-pw, -pw,  4/16,
              pw,  pw,  6/16},
            {-pa, -pa,  6/16,
              pa,  pa,  pl},
        },
    }
end

local function get_formspec(meta)
    local fs, size = aom_inventory.player.get_formspec(nil)
    local y = 12-size.y
    local always_active = (meta and ((meta:get_string("always_active") ~= "")))
    local btn_col = (always_active and "#1a3") or "#a13"
    return table.concat({
        fs,
        "container[", 12-8/2, ",", y-5.5, "]",
        aom_inventory.get_9patch(0, 0, 8, 4, aom_inventory.get_bg9patch_texture("#964253"), "false", "32"),
        ((aom_inventory.get_itemslot_array(4.5, 0.5, 3, 3)) or ""),
        "list[context;main;4.5,0.5;3,3;]",
        ((aom_inventory.get_itemslot_array(3, 0.5, 1, 1)) or ""),
        "list[context;tool;3,0.5;1,1;]",

        "style_type[image_button;bgimg=aom_inv_btn.png\\^\\[multiply:", btn_col, ";bgimg_middle=8;",
        "bgimg_hovered=aom_inv_btn.png\\^\\[multiply:", btn_col, ";bgimg_pressed=aom_inv_btn_press.png\\^\\[multiply:", btn_col, ";",
        "bgcolor_hovered=#eee;bgcolor_pressed=#fff;border=false]",
        "image_button[0.5,2.5;1,1;aom_wire_gui_repeat.png",
        ((always_active and "^[multiply:#4f7") or "^[multiply:#f57") or "",
        ";toggle_always_active; ]",
        -- TL: active ("on" or "off")
        "label[1.5,3;", core.colorize("#ccc", S("Always Active: @1",
        -- TL: active / inactive ("Always Active: @1"), 
        always_active and S("on") or S("off"))), "]",
        "container_end[]",

        "listring[context;tool]",
        "listring[current_player;main]",
        "listring[context;main]",
        "listring[current_player;main]",
    })
end

local function fix_formspec(pos)
    -- set up the formspec and stuff
    local meta = core.get_meta(pos)
    local formspec = get_formspec(meta)
    if meta:get_string("formspec") == formspec then return end
    local inv = meta:get_inventory()
    inv:set_size("main", 9)
    inv:set_size("tool", 1)
    meta:set_string("formspec", formspec)
    meta:set_string("infotext", "Siphon");
    return true
end

local function do_particles(p)
    local d = 0.7
    core.add_particlespawner({
        amount = 30,
        time = 0.01,
        collisiondetection = false,
        collision_removal = false,
        object_collision = false,
        vertical = false,
        texpool = {
            {
                name = "gm_windmills_rocket_smoke.png",
                alpha_tween = {
                    0.0, 1.0,
                    style = "rev",
                    reps = 1,
                },
            }
        },
        -- texture = "gm_windmills_rocket_smoke.png",
        -- glow = 0,
        minpos = vector.new(p.x - d, p.y - d, p.z - d),
        maxpos = vector.new(p.x + d, p.y + d, p.z + d),
        minvel = vector.new(-1, -1, -1),
        maxvel = vector.new( 1,  1,  1),
        minexptime = 0.4,
        maxexptime = 1,
        minsize = 1,
        maxsize = 6,
    })
end

local function do_dig_sound(pos, ndef)
    local sound = ndef.sounds and ndef.sounds.dug
    if not sound then
        sound = aom_sounds.default_stone().dug
    end
    sound = table.copy(sound)
    sound.pos = pos
    sound.max_hear_distance = 5
    sound.gain = 0.1
    core.sound_play(sound.name, sound)
end

local function do_fail_sound(pos, ndef)
    core.sound_play("aom_fire_extinguish", {
        pos = pos,
        max_hear_distance = 5,
        gain = 0.2,
    })
end

local has_aom_pipes = core.get_modpath("aom_pipes") ~= nil
local function move_items(pos)
    if not has_aom_pipes then return end
    local behind_pos = vector.subtract(pos, core.facedir_to_dir(core.get_node(pos).param2))
    local ret = aom_pipes.move_item_to(pos, behind_pos, aom_pipes.item_move_count, {})
    return true
end

local function try_dig(pos, digger)
    local to_pos = vector.add(pos, core.facedir_to_dir(core.get_node(pos).param2))
    local node = core.get_node_or_nil(to_pos)
    if not node then return false end
    if node.name == "air" then return false end
    local meta = core.get_meta(pos)
    local inv = meta:get_inventory()
    local tool_stack = inv:get_stack("tool", 1)
    if tool_stack:get_count() <= 0 then
        tool_stack = ItemStack("aom_tools:stone_pickaxe")
        -- return false
    end
    local ndef = core.registered_nodes[node.name]
    if ndef and (ndef.diggable == false) then
        do_fail_sound(pos, ndef)
        return false
    end
    local tool_capabilities = tool_stack:get_definition().tool_capabilities or {}
    if not core.get_dig_params(ndef.groups, tool_capabilities).diggable then
        do_fail_sound(pos, ndef)
        return false
    end
    local list = core.get_node_drops(node, tool_stack:get_name())
    if list then
        core.set_node(to_pos, {name="air"})
        node_updates.trigger_update(to_pos, digger, "dig")
    else
        return false
    end
    for i, stack in ipairs(list) do
        stack = inv:add_item("main", stack)
        if stack and (stack:get_count() > 0) then
            core.add_item(to_pos, stack)
        end
    end
    do_particles(to_pos)
    do_dig_sound(pos, ndef)
    return true
end

core.register_node("aom_machines:node_digger", {
    description = S("Node Digger"),
    _tt_color = 3,
    _tt_long_desc = S("On wire signal, tries to dig the node in front. The tool in its inventory is used."),
    groups = { cracky = 1, oddly_breakable_by_hand = 2, solid = 1, mechanisms = 1, storage = 1, },
    tiles = {
        "aom_machines_digger.png^[transformR90",
        "aom_machines_digger.png^[transformR270",
        "aom_machines_digger.png",
        "aom_machines_digger.png^[transformFX",
        "aom_machines_digger_front.png",
        "aom_machines_digger_back.png",
    },
    sounds = aom_sounds.default_wood(),
    paramtype = "light",
    sunlight_propagates = true,
    paramtype2 = "facedir",
    drawtype = "nodebox",
    node_box = node_box,
    on_place = aom_util.rotate_and_place_against,
    on_construct = function(pos)
        fix_formspec(pos)
    end,
    on_destruct = function(pos)
        aom_inventory.drop_contents(pos)
        local nt = core.get_node_timer(pos)
        if nt:is_started() then nt:stop() end
    end,
    on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
        fix_formspec(pos)
    end,
    on_timer = function(pos, elapsed)
        move_items(pos)
        try_dig(pos)
        local meta = core.get_meta(pos)
        local nt = core.get_node_timer(pos)
        if meta:get_string("always_active") ~= "" then
            nt:start(1)
        end
    end,
    on_receive_fields = function(pos, formname, fields, sender)
        if fields["toggle_always_active"] then
            local meta = core.get_meta(pos)
            local nt = core.get_node_timer(pos)
            if meta:get_string("always_active") ~= "" then
                meta:set_string("always_active", "")
            else
                meta:set_string("always_active", "1")
                if not nt:is_started() then
                    nt:start(1)
                    nt:set(1, 0.9)
                end
            end
            fix_formspec(pos)
        end
    end,
    _on_wire_input = function(pos, user, source)
        local node = core.get_node_or_nil(pos)
        if not node then return end
        local nt = core.get_node_timer(pos)
        if nt:is_started() then return end
        nt:start(1)
        nt:set(1, 0.2)
    end,
    _has_formspec = true,
})

aom_tcraft.register_craft({
    output = "aom_machines:node_digger",
    items = {
        ["aom_stone:cobble"] = 10,
        ["aom_items:iron_bar"] = 1,
    },
})
