local S = ladders_3d.translator
local register = ladders_3d.register


local nodebox = {
    { -0.4375, -0.5, 0.375, -0.25, 0.5, 0.5 },      -- strut_l
    { 0.25, -0.5, 0.375, 0.4375, 0.5, 0.5 },        -- strut_r
    { -0.25, 0.1875, 0.4375, 0.25, 0.3125, 0.5 },   -- rung_t
    { -0.25, -0.3125, 0.4375, 0.25, -0.1875, 0.5 }, -- rung_b
}


local groups = {
    creative_decoblock = 1,
    level = -3,
    oddly_breakable_by_hand = 3,
}


local ladders = {
    birch = { S('Birch Wood Ladder'), 255 },
    fir =   { S('Fir Wood Ladder'),   96 },
    oak =   { S('Oak Wood Ladder'),   196 }
}


for id,def in pairs(ladders) do
    -- Get needed data
    local base_node = 'rp_default:planks_'..id
    local base_def = core.registered_nodes[base_node]
    local base_texture = base_def.tiles[1]
    local name = def[1]
    local opacity = def[2]

    -- “Stealing” the default ladder’s connectors
    local connectors = ('((+b)^[mask:+s)'):gsub('%+%w', {
        ['+b'] = 'default_ladder_nodebox_front.png',
        ['+s'] = 'ladders_3d_repixture_connectors_mask.png'
    })

    local texture = ('((+b)^(+s^[opacity:64))'):gsub('%+%w', {
        ['+b'] = base_texture,
        ['+s'] = 'ladders_3d_repixture_shading_mask.png',
    })

    local texture_connectors = ('(+t^(+c^[opacity:+o))'):gsub('%+%w', {
        ['+t'] = texture,
        ['+c'] = connectors,
        ['+o'] = opacity
    })

    local inventory_image = ('((+tc^[mask:+im)^+io)'):gsub('%+%w+', {
        ['+tc'] = texture_connectors,
        ['+im'] = 'ladders_3d_repixture_inventory_mask.png',
        ['+io'] = 'ladders_3d_repixture_inventory_outline.png'
    })

    local registered_ladder = register('ladder_'..id, {
        description = name,
        nodebox = { type = 'fixed', fixed = nodebox },
        sounds = base_def.sounds,
        groups = groups,
        image = inventory_image,
        tiles = {
            texture,  -- top
            texture,  -- bottom
            texture,  -- right
            texture,  -- left
            texture,  -- “front” (back)
            texture_connectors, -- “back” (front)
        }
    })

    -- Using Repixture craft registering API
    --
    -- The `rp_crafting` mod that provides the `crafting` API is a mandatory
    -- dependency of `rp_default` which is loaded at this point.
    --
    -- 2 base nodes + 2 fiber = 2 ladders
    -- 1 ladder = 1 base node
    crafting.register_craft({
        output = registered_ladder..' 2',
        items = {
            base_node..' 2',
            'rp_default:fiber 2',
        }
    })
    crafting.register_craft({
        output = base_node..' 1',
        items = {
            registered_ladder..' 1'
        }
    })
end
