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

local creative_setting = minetest.is_creative_enabled()

function minetest.is_creative_enabled(name)
    if not name then return creative_setting end
    local player = minetest.get_player_by_name(name)
    return (player and player:get_meta():get_string("creative") == "true") or false
end

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

function br_core.set_creative_hand(player, bool)
    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
end

function br_core.set_creative(player, bool, force)
    local name = player:get_player_name()
    bool = bool or false -- no nil
    local meta = player:get_meta()
    local is_creative = meta:get_string("creative") == "true"
    local changed = force or (is_creative ~= bool)
    if not changed then return end

    meta:set_string("creative", (bool and "true") or "")

    br_core.set_creative_hand(player, bool)

    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 minetest.is_creative_enabled(player:get_player_name()) or 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()), true)
    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.."."
        elseif param == "ignore" then
            player:get_meta():set_string("seen_creative_warning", "true")
            return true, "Never showing creative warning again."
        else
            return false, "Error: Please use [/creative on] or [/creative off]."
        end
	end
})
