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

local width = 8

local function get_pos(i, o)
    local x = ((i % width + o.x)*2)
    if i % width > 3 then x = x + 2.2 end
    local y = ((math.floor(i/width) + o.y)*2.15)
    return x..","..y
end

local function get_achievements_objects(player)
    local offset = {x=0.5,y=0.3}
    local shadow_offset = {x=0.5,y=0.3}
    local pli = br_core.achievements.get_sorted(player)
    local ret = ""
    if not pli then return "" end
    local i = 0
    for k, achievement in pairs(pli) do
        local def = br_core.achievements.def[achievement.name]
        if def then
            ret = ret.."image["..get_pos(i, shadow_offset)..";1.8,2.16;br_achieve_bg_shadow.png\\^[opacity\\:100]"
            ret = ret.."image["..get_pos(i, offset)..";1.5,1.86;("..def.photo..")]"
            i = i + 1
        else
            minetest.log("warning", "No def for "..achievement.name)
        end
    end
    return ret or ""
end

function br_core.get_inventory_list(o)
    return "list[current_player;main;"..o.x..","..o.y..";6,1;0]"
end

local background = "[combine:512x"..(256+64)..":0,0=br_ui_achievement_background.png"
function br_core.achievements.get_formspec(player)
    return (
        "formspec_version[3]size[20,12.5]position[0.5,0.5]anchor[0.5,0.5]"..
        "background[0,0;0,0;"..background..";true]"..
        "bgcolor[#ffffff00]"..
        get_achievements_objects(player)..
        br_core.get_inventory_list({x=6.5,y=10.5})..
        "listcolors[#f7ebeb80;#f7ebeb10]"
    )
end

function br_core.achievements.show_formspec(player)
    minetest.show_formspec(player:get_player_name(), "achievements", br_core.achievements.get_formspec(player))
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
    if formname == "" then
        -- minetest.chat_send_all(":"..formname..":")
        if fields.openachievements then
            br_core.achievements.show_formspec(player)
        end
    end
end)


local timer = 0.1
minetest.register_globalstep(function(dtime)
    if timer > 0 then timer = timer - dtime
    else timer = 2 end
    for _, player in pairs(minetest.get_connected_players()) do
        if not minetest.is_creative_enabled(player:get_player_name()) then
            local fs = br_core.achievements.get_formspec(player)
            if fs ~= player:get_inventory_formspec() then
                player:set_inventory_formspec(fs)
            end
        end
    end
end)
