local mod = "gems_battle"
local function leave_arena(arena,p_name) end -- removes HUD, sets detach, and removes armor


arena_lib.on_load(mod, function(arena)

    gems_battle.clearobjects(arena)

    minetest.after(.1,function( arena )

        for id,team_data in pairs(arena.teams) do        
            minetest.add_entity(vector.add(arena[team_data.name.."_gem"],vector.new(0,.5,0)), "gems_battle:great_gem", minetest.write_json({
                --mod = mod,
                team_name = team_data.name,
                teamID = id,
                match_id = arena.matchID
            }))

        end

        for _,gem_name in pairs(gems_battle.get_active_team_names(arena)) do
            minetest.add_entity(vector.add(arena[gem_name.."_shop"],vector.new(0,.5,0)), "gems_battle:shopkeeper_"..gem_name, minetest.write_json({
                match_id = arena.matchID
            }))  
        end

        -- attach the players so they cannot move until the time starts. Add nametags.
        for p_name, stats in pairs(arena.players) do 
            local player = minetest.get_player_by_name(p_name)
            if player then 
                local p_pos = player:get_pos()
                local keeper = minetest.add_entity(p_pos,"gems_battle:player_keeper")
                player:set_attach(keeper)

                local team_name = arena.teams[arena.players[p_name].teamID].name
                local icon = minetest.add_entity(p_pos, "gems_battle:gem_nametag", nil)
                icon:set_properties({textures={"item_"..team_name..".png"}})
		        icon:set_attach(minetest.get_player_by_name(p_name), "Head", {x=0, y=7, z=0})
            end
        end

    end,arena)

    arena_lib.HUD_send_msg_all("title", arena, "Get Gems From Gem Droppers, \nBuy Gem Tools at the shops!", 5, nil, 0x71aa34)

    minetest.after(5,function( arena )
        arena_lib.HUD_send_msg_all("title", arena, "Destroy the other teams' Great Gem \nwith a Gem Pick so you can eliminate them!", 5, nil, 0x71aa34)
    end,arena)
end)



arena_lib.on_quit(mod, function(arena, p_name, is_spectator, reason, p_properties)
    gems_battle.remove_hud(arena,p_name)
end)




arena_lib.on_start(mod, function(arena)
    arena.is_started = true
    arena_lib.HUD_send_msg_all("title", arena, "Fight!", 2, nil, 0x71aa34)

    for pl_name,stats in pairs(arena.players) do
        local player = minetest.get_player_by_name(pl_name)
        if player then
            gems_battle.clear_inv(player)
            gems_battle.add_hud(arena,pl_name)
        end
    end
    for sp_name,stats in pairs(arena.spectators) do
        gems_battle.add_hud(arena,sp_name, true)
    end
end)

arena_lib.on_join(mod, function(p_name, arena, as_spectator, was_spectator)
    if arena.is_started and not arena.in_celebration then
        gems_battle.add_hud(arena,p_name,as_spectator)
    end
end)


arena_lib.on_prequit(mod, function(arena, p_name)
    if not arena.spectators[p_name] then
        leave_arena(arena,p_name)
    end
end)


arena_lib.on_time_tick(mod, function(arena)
    if arena.current_time < arena.initial_time - 3 then
        -- handle gem destruction
        for team_id, team_data in ipairs(arena.teams) do
            local team_name = team_data.name
            if arena.teams[team_id].gem_hp == 0 and arena.teams[team_id].gem_exists == true then
                --The great gem is missing! Now the players shall die.
                -- send msg and switch off gem_exists
                local uc = string.upper(team_name)
                arena_lib.send_message_in_arena( arena , 'both' , minetest.colorize(gems_battle.get_color_code(team_name),uc) .. " team's Great Gem has been destroyed!".." ".. minetest.colorize(gems_battle.get_color_code(team_name),uc).." will not respawn!" )
                local numbercolor = tonumber("0x"..string.sub(gems_battle.get_color_code(team_name),2,-1))
                arena_lib.HUD_send_msg_all("title", arena, uc .. " team's Great Gem has been destroyed!", 3, nil, numbercolor)
                arena.teams[team_id].gem_exists = false
            end
        end
    end



    -- heal reveal item wear 
    for p_name, stats in pairs(arena.players) do
        local player = minetest.get_player_by_name(p_name)
        local inv = player:get_inventory()
        local list = inv:get_list("main")
        for idx,i_stack in ipairs(list) do
            local iname = i_stack:get_name()
            if gems_battle.is_one_of(iname,gems_battle.gem_reveals) then
                i_stack:add_wear(-65530/30)
                inv:set_stack("main", idx, i_stack)
            end
        end
    end
    


end)

-- not sure why the on_player_hpchange doesnt catch all deaths, but, here we go, I guess this handles it
arena_lib.on_death(mod, function(arena,p_name,reason)
    gems_battle.on_death(arena, p_name, reason)
end)

arena_lib.on_timeout(mod, function(arena)
    arena_lib.load_celebration(mod, arena)
    arena_lib.HUD_send_msg_all("title", arena, "Time's up! No one won the game.", 3)
end)


arena_lib.on_end(mod, function(arena, winners, is_forced)
    for pl_name ,stats in pairs(arena.players) do
        leave_arena(arena,pl_name)
    end

    for sp_name, stats in pairs(arena.players_and_spectators) do
        gems_battle.remove_hud(arena,sp_name)
    end

    -- delete the game entities
    gems_battle.clearobjects(arena)
end)


arena_lib.on_celebration(mod, function(arena, winners) 
    arena.is_started = false
end)



arena_lib.on_eliminate(mod, function(arena, p_name, xc_name, p_properties) 
    leave_arena(arena,p_name)
end) 



-- LOCAL FUNCTIONS
function leave_arena(arena,p_name, spectator)
    local player = minetest.get_player_by_name(p_name)
    if player then 
        if not spectator then
            player:set_detach()
            armor:remove_all(player)
        end
    end
end
