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

local pl = world_storage:get_key("br_creative") or {}

local creative_setting = minetest.is_creative_enabled()

function minetest.is_creative_enabled(name)
    if not name then return creative_setting end
    return (pl[name] and (pl[name].is_creative_enabled))
end

local function get_shell()
    return {
        is_creative_enabled = false
    }
end

function br_core.set_creative(player, bool, force)
    local name = player:get_player_name()
    if not pl[name] then pl[name] = {} end
    local changed = force or (pl[name].is_creative_enabled ~= (bool or false))
    if not changed then return end
    world_storage:set_key("br_creative", pl)

    pl[name].is_creative_enabled = bool or false

    local inv = player:get_inventory()
    inv:set_size("hand", 1)
    if bool then
        inv:set_stack("hand", 1, ItemStack("br_core:creative_hand"))
    else
        inv:set_stack("hand", 1, ItemStack(""))
    end

    br_core.update_player_formspec(player)
end

minetest.register_on_joinplayer(function(player, last_login)
    if not last_login then
        br_core.set_creative(player, creative_setting or br_core.mapgen=="flat", true)
    -- make sure not to shrink existing players' inventories and destroy their items if migrating from old save
    elseif (not pl[player:get_player_name()]) and br_core.mapgen=="flat" then
        br_core.set_creative(player, true, true)
    else
        br_core.set_creative(player, minetest.is_creative_enabled(player:get_player_name()))
    end
end)

minetest.register_privilege("creative", {
	description = S("Lets players change their creative status"),
	give_to_singleplayer = true
})

minetest.register_chatcommand("creative", {
	params = "/creative on|off",
	description = S("Turns on or off some features"),
	privs = {creative=true},
	func = function(name, param)
        local player = minetest.get_player_by_name(name)
        if param == "off" then
            br_core.set_creative(player, false)
            return true, "Set creative off for "..name
        elseif param == "on" then
            br_core.set_creative(player, true)
            return true, "Set creative on for "..name
        else
            return false, "Error: Please use [/creative on] or [/creative off]"
        end
	end
})
