bounty = {}
bounty.file = core.get_worldpath() .. '/bounty.txt'
bounty.data = {}
bounty.prizes = false --determines if prizes or amount per points game-mechanic is used
if true then
    bounty.prizes = 'currency:minegeld_100'
    bounty.points_per_prize = 100 --per 100 points you get a default:steel_ingot
else
    bounty.prizes = {
        [20] = 'default:wood 50',        -- for bounties that are higher then 100 iron ingots are given
        [50] = 'default:cobble 50',      -- for bounties that are higher then 150 gold ingots are given
        [70] = 'default:stone 40',       -- for bounties that are higher then 150 gold ingots are given
        [100] = 'default:steel_ingot 2', -- for bounties that are higher then 150 gold ingots are given
        [200] = 'default:steel_ingot 5'  -- etc...
    }
end

bounty.penalize = function(player_name) --set the penalty
    --example of a penalty (revoke all privs ecept interact)
    --core.set_player_privs(player_name, { shout = true })
    bounty.unregister(player_name)
    --end of example
end

bounty.load = function()
    local data_file = io.open(bounty.file, 'r')
    if data_file then
        local data_stri = data_file:read();
        bounty.data = core.parse_json(data_stri)
        if bounty.data == nil then
            bounty.data = {}
        end
        data_file:close()
    end
end
bounty.load()

bounty.save = function()
    local data_stri = core.write_json(bounty.data)
    local data_file = io.open(bounty.file, 'w')
    if data_file ~= nil then
        data_file:write(data_stri)
        data_file:close()
    else
        core.log('error', '[bounty] Could not open ' .. bounty.file .. ' with write permission')
    end
end

bounty.set_nametag_color = function(player_name)
    local player = minetest.get_player_by_name(player_name)
    local props = player:get_properties()
    if bounty.data[player_name] > 10000 then
        player:set_properties({ nametag_color = "#ffffff" })
    elseif bounty.data[player_name] > 1000 then
        player:set_properties({ nametag_color = "#ff0000" })
    elseif bounty.data[player_name] > 500 then
        player:set_properties({ nametag_color = "#ffa500" })
    elseif bounty.data[player_name] > 100 then
        player:set_properties({ nametag_color = "#ffff00" })
    else
        if not core.check_player_privs(player_name, { fediauth_authorized = true }) then
            player:set_properties({ nametag_color = "#00ff00" })
        else
            player:set_properties({ nametag_color = "#0000ff" })
        end
    end
end

bounty.increase = function(player_name, amount)
    if bounty.data[player_name] then
        bounty.data[player_name] = bounty.data[player_name] + amount
    else
        bounty.register(player_name, amount)
    end
    bounty.save()
    bounty.notify(player_name, amount)
    bounty.set_nametag_color(player_name)
end

bounty.decrease = function(player_name, amount)
    if bounty.data[player_name] then
        if bounty.data[player_name] - amount < 0 then
        else
            bounty.data[player_name] = bounty.data[player_name] - amount
        end
    end
    bounty.notify(player_name, -amount)
    bounty.save()
    bounty.set_nametag_color(player_name)
end

bounty.register = function(player_name, amount)
    bounty.data[player_name] = amount
    bounty.save()
end

bounty.unregister = function(player_name)
    if bounty.data[player_name] then
        bounty.data[player_name] = nil
        bounty.save()
    end
end

bounty.notify = function(player_name, amount)
    if bounty.data[player_name] + amount <= 0 then
        core.chat_send_all(player_name .. " no longer has a bounty")
    end
    if type(bounty.prizes) == 'string' then
        core.chat_send_all(player_name .. "'s bounty is $" .. bounty.get_player_bounty(player_name):split(" ")[1] .. "00")
    else
        for key, value in pairs(bounty.prizes) do
            if bounty.data[player_name] > key and bounty.data[player_name] - amount < key then
                core.chat_send_all(player_name .. "'s bounty has changed to $" ..
                    bounty.get_player_bounty(player_name):split(" ")[1] .. "00")
                break
            end
        end
    end
end

bounty.drop_prize = function(player)
    local player_name = player:get_player_name()
    local prize = bounty.get_player_bounty(player_name)
    core.log('info', prize)
    core.item_drop(ItemStack(prize), player, player:get_pos())
    core.log('info', prize)
    bounty.penalize(player_name)
end

bounty.get_player_bounty = function(player_name)
    local prize = ' has no bounty'
    if type(bounty.prizes) == 'string' then
        local amount = math.floor(bounty.data[player_name] / bounty.points_per_prize)
        if bounty.data[player_name] >= bounty.points_per_prize then
            prize = bounty.prizes .. ' ' .. amount
        end
    else
        local order = 0
        for key, value in pairs(bounty.prizes) do
            if order < key and bounty.data[player_name] > key then
                order = key
                prize = bounty.prizes[key]
            end
        end
    end
    return prize
end

bounty.player_exists = function(player_name)
    if not minetest.get_player_by_name(player_name) then
        return false
    else
        return true
    end
end

--chatcommands for testing purposes
core.register_chatcommand('bounty', {
    description = 'Place bounty on offenders and increasing the bounty by 100',
    privs = { interact = true },
    func = function(name, params)
        if bounty.player_exists(params) then
            local inv = core.get_inventory({ type="player", name=name })
            if inv:contains_item("main", "currency:minegeld_100") then
                inv:remove_item("main", "currency:minegeld_100")
                bounty.increase(params, 100)
            else
                core.chat_send_player(name, "Insufficient funds: $100 minegeld needed")
            end
        else
            core.chat_send_player(name, "Player " .. params .. " does not exist")
        end
    end
})

core.register_chatcommand('forgive', {
    description = 'Forgive offender and decrease bounty by 100',
    privs = { interact = true },
    func = function(name, params)
        if bounty.player_exists(params) then
            bounty.decrease(params, 100)
        else
            core.chat_send_player(name, "Player " .. params .. " does not exist")
        end
    end
})

core.register_chatcommand('bounties', {
    params = '',
    description = 'Show all offenders and their bounty',
    privs = { interact = true },
    func = function(name, params)
        for key, value in pairs(bounty.data) do
            core.chat_send_player(name, key .. ' - ' .. bounty.get_player_bounty(key))
        end
    end
})

core.register_on_dieplayer(function(player)
    if bounty.data[player:get_player_name()] then --check if is perpetrator
        bounty.drop_prize(player)
    end
end)

core.register_on_joinplayer(function(player)
    bounty.set_nametag_color(player:get_player_name())
end
