bb_menu = {}

minetest.register_on_joinplayer(function(player)
    local p_name = player:get_player_name()
        
    -- set their inv formspec --show the menu when they join
    player:set_inventory_formspec(bb_loop.get_inv_formspec(p_name))
    minetest.show_formspec(p_name, "bb_menu:firstjoin", bb_loop.get_inv_formspec(p_name))
end)



function bb_menu.get_leaderboard_order()

    local leaderboard = bb_loop.leaderboard
    local players_by_score = {}

    for p_name,wins in pairs(leaderboard) do
        if players_by_score[wins] then
            table.insert(players_by_score[wins],p_name)
        else
            players_by_score[wins] = {p_name}
        end
    end

    local scores_array = {}

    for wins,p_names in pairs(players_by_score) do --wins is a num, p_names is a tbl
        table.insert(scores_array, wins)
    end
    --sorts the scores from greatest to least so I know what order to get the keys from blayers_by_score in
    table.sort(scores_array, function(a,b) return a > b end)
    return scores_array,players_by_score

end





-- override the bb_loop function
-- get the inventory formspec, which contians the leaderboard, and color choice, and a glossary





function bb_loop.get_inv_formspec(p_name)

    local player = minetest.get_player_by_name(p_name)
    if not player then return "" end

    local status = ""

    if bb_loop.gamestate == "waiting" then
        status = "WAITING FOR OTHER PLAYERS"
    end
    if bb_loop.gamestate == "loading" then
        status = "LOADING ARENA"
    end
    if bb_loop.gamestate == "running" then
        local meta = player:get_meta()
        local p_status = meta:get_string("status")
         
        status = "A GAME IS ONGOING"

        if p_status == "inactive" then
            status = status.." WAITING TO JOIN NEXT ROUND"
        end
        if p_status == "playing" then
            status = "PLAYING"
        end
        if p_status == "dead" then
            status = status .. " YOU ARE DEAD"
        end
    end

    -- get the player's current textures for player model selection
    local textures = {"white.png^[colorize:"..bb_playermodel.saved_colors[p_name]..":255","player_parts.png"}
    local player_textures = textures[1]..","..textures[2]

  

        -- build the leaderboard 

        local leaderfs = ""
        local leadercount = 1 -- counter for building fs
        local scores_array,players_by_score = bb_menu.get_leaderboard_order()
        if scores_array and players_by_score then
            local listcolor = "#dff6f566"
            for _ , score in ipairs(scores_array) do
                
                --local pls_str = ""
                local pls_list = players_by_score[score]
                for _,p_name in ipairs(pls_list) do
                    if listcolor == "#dff6f566" then listcolor = "#cfc6b866" else listcolor = "#dff6f566" end
                    local p_color = bb_playermodel.saved_colors[p_name] or "#dff6f5"
                    leaderfs = leaderfs ..
                    "box[.8,"..tostring(leadercount-.5)..";1.9,.9;"..listcolor.."]"..
                    "box[2.8,"..tostring(leadercount-.5)..";16,.9;"..listcolor.."]"..
                    "label[1,"..leadercount..";"..minetest.colorize(p_color,score).."]"..
                    "label[3.2,"..leadercount..";"..minetest.colorize(p_color,p_name).."]"
                    --"textlist[2,"..tostring(leadercount - 0.5) ..";17,1.5;score_"..score..";"..pls_str.."]"
                    leadercount = leadercount + 1
                end
                
                
            end
        end
                
            





    local fs = "formspec_version[4]"..
    "size[25,20]"..
    "position[0.5,0.5]"..
    "bgcolor[#0000]"..
    "background9[0,0;25,20;bb_player_gui_bg.png^[opacity:50;false;50]"..
    "scrollbaroptions[max=1070;thumbsize=200;arrows=hide]"..
    "scrollbar[24,.5;.3,19;vertical;mainscroll;0]"..
    "scroll_container[.5,.5;23,19;mainscroll;vertical;]"..
    
        "image[1.2,1;21,4;bb_logo.png]"..
        "box[1.2,5.5;21,1;#302c2eCC]"..
        "image_button[1.2,5.5;21,1;blank.png;status_button;"..status..";false;false;blank.png]"..
    
    
        
        -- was 16
        "box[1.2,7;21,8;#302c2eCC]"..
        "box[1.2,7;21,1;#5a5353CC]"..
        "image_button[1.2,7;21,1;blank.png;color_button;CHOOSE YOUR BLOCKER;false;false;blank.png]"..
    
        "image_button[2.2,10;1,1;bb_player_arrow.png;color_left;;false;false;]"..
        "image_button[20.2,10;1,1;bb_player_arrow.png^[transformFX;color_right;;false;false;]"..
        "model[8.2,9;6,5;player_model;bb_character.b3d;"..player_textures..";0,-180;true;true;]"..
    
        
        --was 7
        "box[1.2,16;21,8;#302c2eCC]"..
        "box[1.2,16;21,1;#5a5353CC]"..
        "image_button[1.2,16;21,1;blank.png;leaderboard_button;LEADER BOARD;false;false;blank.png]"..
        
        "scrollbaroptions[max="..tostring(leadercount*8)..";thumbsize="..tostring(leadercount)..";arrows=hide]"..
        "scrollbar[21.5,17.5;.3,6;vertical;leaderscroll;0]    "..
        "scroll_container[2,17.5;19.5,6;leaderscroll;vertical]"..
    
            leaderfs ..

        "scroll_container_end[]"..
    
        "box[1.2,25;21,100;#302c2eCC]"..
        "box[1.2,25;21,1;#5a5353CC]"..
        "image_button[1.2,25;21,1;blank.png;bombs_button;BOMBS;false;false;blank.png]"..
        "model[2.25,27;2.5,2.5;bomb_model;bb_bomb.b3d;bb_bomb_texture.png;nil;true;true;]"..
        "box[5.5,27;16,3;#5a5353CC]"..
        "textarea[5.75,27.25;15.5,2.5;;;Place bombs with SPACE.  Bombs explode in orthagonal directions.  Once placed, it blocks your path, so be careful where you place it.]"..
    
        "box[1.2,31;21,1;#5a5353CC]"..
        "image_button[1.2,31;21,1;blank.png;powerups_button;POWERUPS;false;false;blank.png]"..
    
        "image[2,33;2.5,2.5;bb_powerup_bomb.png]"..
        "box[5.5,33;16,3;#5a5353CC]"..
        "textarea[5.75,33.25;15.5,2.5;;;Bomb items indicate your ability to place a bomb. Having more means you can place more bombs at once (bombs are removed until they explode). Collect them all!]"..
    
        "image[2,37;2.5,2.5;bb_powerup_power.png]"..
        "box[5.5,37;16,3;#5a5353CC]"..
        "textarea[5.75,37.25;15.5,2.5;;;TNT indicates the size of the explosion your bombs will make. Collect more for a bigger bang!]"..
    
        "image[2,41;2.5,2.5;bb_powerup_fast.png]"..
        "box[5.5,41;16,3;#5a5353CC]"..
        "textarea[5.75,41.25;15.5,2.5;;;Shoes indcate how fast you can go. Collect more to speed around the map!]"..
    
        "image[2,45;2.5,2.5;bb_powerup_extra_life.png]"..
        "box[5.5,45;16,3;#5a5353CC]"..
        "textarea[5.75,45.25;15.5,2.5;;;Hearts give protection against bomb blasts. One at a time, please!]"..
    
        "image[2,49;2.5,2.5;bb_powerup_kick.png]"..
        "box[5.5,49;16,3;#5a5353CC]"..
        "textarea[5.75,49.25;15.5,2.5;;;Fist gives you the ability to push bombs. Without being inside the bomb, stand next to it and use PUNCH or LMB to give it a shove!]"..
    
        "image[2,53;2.5,2.5;bb_powerup_throw.png]"..
        "box[5.5,53;16,3;#5a5353CC]"..
        "textarea[5.75,53.25;15.5,2.5;;;A Spring allows you to throw bombs that you are in 2 blocks, even if they land inside a block. Use SPACE, and instead of placing a new bomb, you will throw the bomb that you are in.]"..
    
        "image[2,57;2.5,2.5;bb_powerup_resurect.png]"..
        "box[5.5,57;16,3;#5a5353CC]"..
        "textarea[5.75,57.25;15.5,2.5;;;If a player gets a Pheonix, any players who have died are resurrected, with starting items. Give your friends a hand!]"..
    
        "image[2,61;2.5,2.5;bb_powerup_multidir.png]"..
        "box[5.5,61;16,3;#5a5353CC]"..
        "textarea[5.75,61.25;15.5,2.5;;;Compass makes your explosions diagonal as well as orthagonal. Use with caution, but this is a nice way to surprise people who think they're safe. Only 3 uses.]"..
    
        "box[1.2,65;21,1;#5a5353CC]"..
        "image_button[1.2,65;21,1;blank.png;handicaps_button;HANDICAPS;false;false;blank.png]"..
        "image_button[1.2,66;21,1;blank.png;handicapsinfo_button;All handicaps are time-limited;false;false;blank.png]"..
        "image_button[1.2,67;21,1;blank.png;handicapsinfo_button;and can be removed by getting any powerup;false;false;blank.png]"..
    
        "image[2,69;2.5,2.5;bb_powerup_no_placebomb.png]"..
        "box[5.5,69;16,3;#5a5353CC]"..
        "textarea[5.75,69.25;15.5,2.5;;;You can't place it. Sorry.]"..
    
        "image[2,73;2.5,2.5;bb_powerup_slow.png]"..
        "box[5.5,73;16,3;#5a5353CC]"..
        "textarea[5.75,73.25;15.5,2.5;;;You'll win the race, but slowly.]"..
    
        "image[2,77;2.5,2.5;bb_powerup_superfast.png]"..
        "box[5.5,77;16,3;#5a5353CC]"..
        "textarea[5.75,77.25;15.5,2.5;;;Too much energy, don't you think?]"..
    
        "image[2,81;2.5,2.5;bb_powerup_party.png]"..
        "box[5.5,81;16,3;#5a5353CC]"..
        "textarea[5.75,81.25;15.5,2.5;;;Time for a fireworks show!]"..
    
        "image[2,85;2.5,2.5;bb_powerup_weird_control.png]"..
        "box[5.5,85;16,3;#5a5353CC]"..
        "textarea[5.75,85.25;15.5,2.5;;;Ugh, can't move right. Was it something I ate?]"..
    
    
        "box[1.2,89;21,1;#5a5353CC]"..
        "image_button[1.2,89;21,1;blank.png;map_button;MAP;false;false;blank.png]"..
    
        "image[2,91;2.5,2.5;bb_nodes_floor.png]"..
        "box[5.5,91;16,3;#5a5353CC]"..
        "textarea[5.75,91.25;15.5,2.5;;;The Floor. It's solid. That means you can't fall thru it.]"..
    
        "image[2,95;2.5,2.5;blank.png]"..
        "box[5.5,95;16,3;#5a5353CC]"..
        "textarea[5.75,95.25;15.5,2.5;;;This is Air. Its not solid. If you think it is, then, please, try walking on it.]"..
    
        "image[2,99;2.5,2.5;bb_nodes_floor_with_arrow.png]"..
        "box[5.5,99;16,3;#5a5353CC]"..
        "textarea[5.75,99.25;15.5,2.5;;;The arrow pushes bombs that touch it.]"..
    
        "image[2,103;2.5,2.5;bb_nodes_floor_with_mortar.png]"..
        "box[5.5,103;16,3;#5a5353CC]"..
        "textarea[5.75,103.25;15.5,2.5;;;The Mortar. It throws bombs to a random location on the map.]"..
    
        "image[2,107;2.5,2.5;bb_nodes_ice.png]"..
        "box[5.5,107;16,3;#5a5353CC]"..
        "textarea[5.75,107.25;15.5,2.5;;;Ohh, Slippery! Watch out!]"..
    
        "image[2,111;2.5,2.5;bb_nodes_brick.png]"..
        "box[5.5,111;16,3;#5a5353CC]"..
        "textarea[5.75,111.25;15.5,2.5;;;This block can be removed with explosions. It might drop an item!]"..
    
        "image[2,115;2.5,2.5;bb_nodes_crate.png]"..
        "box[5.5,115;16,3;#5a5353CC]"..
        "textarea[5.75,115.25;15.5,2.5;;;It contains an item, if you explode it.]"..
    
        "image[2,119;2.5,2.5;bb_nodes_wall.png]"..
        "box[5.5,119;16,3;#5a5353CC]"..
        "textarea[5.75,119.25;15.5,2.5;;;Tough stuff. You can't break this wall.]"..
    

    "scroll_container_end[]"

    return fs


end


-- dont repeat yourself (used below)
local function save_new_color(p_name,player,new_idx)
    
    bb_playermodel.saved_colors[p_name] = bb_playermodel.player_colors_avail[new_idx]
    --save for future use
    bb_playermodel.savecolors()
    -- save the new texture
    bb_playermodel.textures[p_name] = {"white.png^[colorize:"..bb_playermodel.saved_colors[p_name]..":255","player_parts.png"}
    -- dont do a live update if they have clear textures anyways
    local is_playing = true 
    if player:get_properties().textures[1] == "blank.png" then
        is_playing = false
    end
    if is_playing then
        --live update
        player:set_properties({textures=bb_playermodel.textures[p_name]})
    end

end



minetest.register_on_player_receive_fields(function(player, formname, fields)
    if formname ~= "" then
        if formname ~= "bb_menu:firstjoin" then return end
    end

    local p_name = player:get_player_name()
    -- color change right button
    if fields.color_right then
        -- change the player's color, incrementing up the index

        --determine the new texture color idx
        local old_color = bb_playermodel.saved_colors[p_name]
        local old_idx = 1
        for idx , color in pairs(bb_playermodel.player_colors_avail) do
            if color == old_color then 
                old_idx = idx 
            end
        end
        local max_idx = #bb_playermodel.player_colors_avail
        local new_idx
        if old_idx == max_idx then
            new_idx = 1 
        else
            new_idx = old_idx + 1
        end

        -- save the new color
        save_new_color(p_name,player,new_idx)
        player:set_inventory_formspec(bb_loop.get_inv_formspec(p_name))
        if formname == "bb_menu:firstjoin" then
            minetest.show_formspec(p_name, "bb_menu:firstjoin", bb_loop.get_inv_formspec(p_name))
        end

    end

    --color change left button
    if fields.color_left then
        -- change the player's color, going down the index

        --determine the new texture color idx
        local old_color = bb_playermodel.saved_colors[p_name]
        local old_idx = 1
        for idx , color in pairs(bb_playermodel.player_colors_avail) do
            if color == old_color then 
                old_idx = idx 
            end
        end
        local min_idx = 1
        local new_idx
        if old_idx == min_idx then
            new_idx = #bb_playermodel.player_colors_avail 
        else
            new_idx = old_idx - 1
        end

        -- save the new color
        save_new_color(p_name,player,new_idx)
        
        player:set_inventory_formspec(bb_loop.get_inv_formspec(p_name))
        if formname == "bb_menu:firstjoin" then
            minetest.show_formspec(p_name, "bb_menu:firstjoin", bb_loop.get_inv_formspec(p_name))
        end
    end


end)