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


local warpberry_box = {
    type = "fixed",
    fixed = {
        -4/16, -8/16, -4/16,
        4/16, 4/16, 4/16,
    }
}

local warpberry_variants = {}

local function random_grow_time(mult)
    return (math.random() * 60 + 120) * (mult or 1)
end

local function grow_warpberry(pos, node, active_object_count, active_object_count_wider)
    pmb_util.did_abm("crop")
    minetest.swap_node(pos, {name="pmb_flora:warpberry_bush_fruit"})
end

minetest.register_craftitem("pmb_flora:warpberry_purple", {
    description = pmb_util.desc(S("Warpberry"), "blue"),
    _tt_long_desc = S("Teleports you to where you last ate a Gold Warpberry"),
    inventory_image = "pmb_warpberry_purple.png",
    groups = { item_warpberry = 1, craftitem = 1, warpberry = 1, produce = 1, },
})
minetest.register_craftitem("pmb_flora:warpberry_gold", {
    description = pmb_util.desc(S("Warpberry"), "blue"),
    _tt_long_desc = S("Teleports you to where you last ate a Purple Warpberry"),
    inventory_image = "pmb_warpberry_gold.png",
    groups = { item_warpberry = 1, craftitem = 1, warpberry = 1, produce = 1, },
})

minetest.register_craft({
    output = "pmb_flora:warpberry_purple",
    type = "shapeless",
    recipe = {"pmb_flora:warpberry_gold"},
})
minetest.register_craft({
    output = "pmb_flora:warpberry_gold",
    type = "shapeless",
    recipe = {"pmb_flora:warpberry_purple"},
})

local on_eat_func = pmb_food.eat({
    ["regeneration_8"] = 8*4+1,
})

local function do_sound(object, file, gain)
    minetest.sound_play(file, {
        gain = gain or 0.3,
        object = object
    })
end

local function start_teleport_sequence(user, data)
    if data and data.pos then
        pmb_statusfx.apply_status(user, "blindness", 8.5, {blend_in=4, blend_out=0.1})
        do_sound(user, "pmb_flora_warpberry_teleport_pre", 0.1)
        minetest.after(5, function()
            if (not user) then return end
            do_sound(user, "pmb_flora_warpberry_teleport_long", 0.3)
        end)
        minetest.after(8, function()
            if (not user) or (not data.pos) then return end
            user:set_pos(data.pos)
            pmb_statusfx.apply_status(user, "blindness", 8, {blend_in=0.01, blend_out=8})
        end)
    end
end

pmb_util.register_wield_use_delay("pmb_flora:warpberry_gold", {
    windup = 3,
    sound = {
        name = "pmb_food_munch",
        gain = 0.2,
        max_hear_distance = 10,
        pitch = 0.85
    },
    sound_per_sec = 1.5,
    on_use = function(itemstack, user, pointed_thing)
        itemstack = on_eat_func(itemstack, user, pointed_thing)
        if not minetest.is_player(user) then return itemstack end
        local meta = user:get_meta()
        meta:set_string("pmb_flora:warpberry_gold", minetest.serialize({pos=user:get_pos()}))

        -- handle teleport
        local data = minetest.deserialize(meta:get_string("pmb_flora:warpberry_purple"))
        start_teleport_sequence(user, data)
    end
})
pmb_util.register_wield_use_delay("pmb_flora:warpberry_purple", {
    windup = 3,
    sound = {
        name = "pmb_food_munch",
        gain = 0.2,
        max_hear_distance = 10,
        pitch = 0.85
    },
    sound_per_sec = 1.5,
    on_use = function(itemstack, user, pointed_thing)
        itemstack = on_eat_func(itemstack, user, pointed_thing)
        if not minetest.is_player(user) then return itemstack end
        local meta = user:get_meta()
        meta:set_string("pmb_flora:warpberry_purple", minetest.serialize({pos=user:get_pos()}))

        -- handle teleport
        local data = minetest.deserialize(meta:get_string("pmb_flora:warpberry_gold"))
        start_teleport_sequence(user, data)
    end
})


minetest.register_node("pmb_flora:warpberry_seeds", {
    description = pmb_util.desc(S("Warpberry Seed"), "grey"),
    _tt_long_desc = S("Can be planted"),
    inventory_image = "pmb_warpberry_seeds.png",
    wield_image = "pmb_warpberry_seeds.png",
    drawtype = "airlike",
    walkable = false,
    paramtype = "light",
    tiles = {
        "pmb_warpberry_stem.png"
    },
    after_place_node = function(pos, placer, itemstack, pointed_thing)
        minetest.set_node(pos, {name="pmb_flora:warpberry_stem"})
        local nt = minetest.get_node_timer(pos)
        nt:start(random_grow_time())
    end,
    is_ground_content = true,
    sunlight_propagates = true,
    groups = { item_warpberry_seeds = 1, },
})

local function place_from_stem(pos)
    local above = vector.offset(pos, 0, 1, 0)
    local above_node = minetest.get_node(above)
    if not minetest.registered_nodes[above_node.name].buildable_to then return true end

    minetest.set_node(above, {name="pmb_flora:warpberry_bush"})

    local nt = minetest.get_node_timer(above)
    if nt:is_started() then return false end
    nt:start(random_grow_time())
end

minetest.register_lbm({
    name = "pmb_flora:warpberry_add_bush",
    nodenames = {"pmb_flora:warpberry_stem"},
    run_at_every_load = false,
    action = function(pos, node, dtime_s)
        place_from_stem(pos)
    end,
})

minetest.register_node("pmb_flora:warpberry_stem", {
    description = pmb_util.desc(S("Warpberry Plant"), "grey"),
    _tt_long_desc = S("Needs sunlight to grow"),
    drawtype = "plantlike",
    walkable = false,
    waving = 1,
    paramtype = "light",
    paramtype2 = "meshoptions",
    inventory_image = "pmb_warpberry_stem.png",
    wield_image = "pmb_warpberry_stem.png",
    is_ground_content = true,
    sunlight_propagates = true,
    selection_box = warpberry_box,
    groups = { nature = 1, attached_node = 1, item_warpberry_plant = 1, oddly_breakable_by_hand = 1, snappy = 1, flora = 1, },
    drop = {
        max_items = 1,
        items = {
            {
                items = {"pmb_flora:warpberry_seeds"},
                -- rarity = 1
            },
        },
    },
    tiles = {
        "pmb_warpberry_stem.png"
    },
    buildable_to = false,
    sounds = pmb_sounds.default_plant(),
    on_timer = function(pos, elapsed)
        place_from_stem(pos)
    end,
    _on_node_update = function(pos, cause, user, count, payload)
        local nt = minetest.get_node_timer(pos)
        if nt:is_started() then return false end
        nt:start(random_grow_time(3))
    end,
    on_place = function(itemstack, placer, pointed_thing)
        return pmb_util.only_place_above(itemstack, placer, pointed_thing, {"soil"})
    end,
})

minetest.register_node("pmb_flora:warpberry_bush", {
    description = pmb_util.desc(S("Warpberry Bush"), "grey"),
    drawtype = "allfaces_optional",
    waving = 1,
    tiles = {
        "pmb_warpberry_bush.png"
    },
    -- special_tiles = tiles_simple,
    paramtype = "light",
    groups = { oddly_breakable_by_hand = 1, nature = 1, snappy = 1, solid = 1, flammable = 1 },
    is_ground_content = false,
    drop = {
      max_items = 2,
      items = {
        {
            items = {"pmb_flora:warpberry_seeds"},
            rarity = 7,
        },
        {
            items = {"pmb_flora:warpberry_seeds 2"},
            rarity = 9,
        },
      },
    },
    sounds = pmb_sounds.default_plant(),
    _on_node_update = function(pos, cause, user, count, payload)
        if (cause == "dig") and (minetest.get_node(vector.offset(pos, 0, -1, 0)).name ~= "pmb_flora:warpberry_stem") then
            minetest.dig_node(pos)
        end
        local nt = minetest.get_node_timer(pos)
        if nt:is_started() then return false end
        nt:start(random_grow_time())
    end,
    on_timer = function(pos, elapsed)
        minetest.swap_node(pos, {name="pmb_flora:warpberry_bush_fruit"})
    end,
})

minetest.register_node("pmb_flora:warpberry_bush_fruit", {
    description = pmb_util.desc(S("Warpberry Bush"), "grey"),
    drawtype = "allfaces_optional",
    waving = 1,
    tiles = {
        "pmb_warpberry_bush_fruit.png"
    },
    -- special_tiles = tiles_simple,
    paramtype = "light",
    groups = { oddly_breakable_by_hand = 1, nature = 1, snappy = 1, solid = 1, flammable = 1 },
    is_ground_content = false,
    drop = {
      max_items = 2,
      items = {
        {
            items = {"pmb_flora:warpberry_seeds"},
            rarity = 7,
        },
        {
            items = {"pmb_flora:warpberry_seeds 2"},
            rarity = 9,
        },
        {
            items = {"pmb_flora:warpberry_gold"},
        },
      },
    },
    sounds = pmb_sounds.default_plant(),
    on_punch = function(pos, node, puncher, pointed_thing)
        if pmb_util.give_to(puncher, ItemStack("pmb_flora:warpberry_gold")) then
            minetest.swap_node(pos, {name="pmb_flora:warpberry_bush"})
            local nt = minetest.get_node_timer(pos)
            nt:start(random_grow_time())
        end
    end,
    _on_node_update = function(pos, cause, user, count, payload)
        if (cause == "dig") and (minetest.get_node(vector.offset(pos, 0, -1, 0)).name ~= "pmb_flora:warpberry_stem") then
            minetest.dig_node(pos)
        end
    end,
})

-- grow warpberry
minetest.register_abm({
    nodenames = {"group:warpberry_growing"},
    interval = 10.0, --10
    chance = 50, --50
    action = grow_warpberry,
})

-- grow warpberry faster near water?
minetest.register_abm({
    nodenames = {"group:warpberry_growing"},
    neighbors = {"group:water"},
    interval = 10.0, --10
    chance = 40, --50
    action = grow_warpberry,
})


