local S = minetest.get_translator("gems_battle")

local function is_one_of(var,tbl) end


--===========  GET COLOR CODES   ===============
-- returns the color code of a team name

gems_battle.get_color_code = function(team_name,pale,as_number)
    
    local codes = {
        ruby        ={reg="#e6482e",pale="#f6583e"},
        sapphire    ={reg="#3978a8",pale="#4988b8"},
        emerald     ={reg="#71aa34",pale="#81ba44"},
        opal        ={reg="#f4b41b",pale="#f7c42b"},
    }
    if team_name and is_one_of(team_name, gems_battle.team_names) then
        local ret
        if pale then
            ret = codes[team_name].pale
        else
            ret = codes[team_name].reg
        end
        if as_number then
            ret = tonumber("0x".. string.sub(ret,2), 16)
        end
        return ret
    end
end



--===========  on_death   ===============
--what happens when a player dies in the arena
--if their team's gem exists, then they respawn. If not, then they are eliminated

gems_battle.on_death = function(arena, p_name, reason )
    local p_team_id = arena.players[p_name].teamID
	local p_team = arena.teams[ p_team_id ].name
    local player = minetest.get_player_by_name( p_name )
    if player then
        local pos = player:get_pos()
        local elems = armor:get_weared_armor_elements (player)
        if elems then
            for elem , item in pairs(elems) do
                armor.drop_armor (pos, item)
                armor:unequip(player, item)
            end
        end
        -- thx ElCeejo!
        local inv = player:get_inventory()
        local list = inv:get_list("main")
        for k, v in pairs(list) do
            local obj = minetest.add_item(pos, v)
            if obj then
                obj:set_velocity({
                    x = math.random(-2, 2),
                    y = math.random(1, 2),
                    z = math.random(-2, 2)
                })
            end
            inv:remove_item("main", v)
        end
    end

    local puncher_name
    if reason and reason.type and reason.type == "punch" and reason.object and reason.object:is_player() then
        puncher_name = reason.object:get_player_name()
    end

    if arena.teams[ p_team_id ].gem_exists == false then
        -- eliminate player
        -- get the killer's name if possible
        if #arena_lib.get_players_in_team(arena, p_team_id, false) == 1 and #arena_lib.get_active_teams(arena) > 2 then
            local team_name = arena.teams[p_team_id].name
            arena_lib.HUD_send_msg_all("title", arena, S("@1 team has been eliminated!", gems_battle.get_capname(team_name)), 3, nil, gems_battle.get_color_code(team_name,false,true))
        end
        arena_lib.remove_player_from_arena(p_name, 1, puncher_name, nil)
        
    else
        -- send the player back to one of his team's spawners if the tower exists
        local player = minetest.get_player_by_name( p_name )
        minetest.after(0,function()
            if player then
                minetest.close_formspec(p_name , "")
                player:set_pos(arena.jail)
                player:set_hp(minetest.PLAYER_MAX_HP_DEFAULT)
            end
        end)

        player:set_pos(arena.jail)
        arena.players[p_name].in_jail = true
        arena.players[p_name].jail_time = 10
        arena.players[p_name].last_puncher = puncher_name

        -- player:set_pos( arena_lib.get_random_spawner( arena , p_team_id ) )

        arena_lib.HUD_send_msg("title", p_name, S("You Died!"), 2, nil, 0xA93B3B)
    end
end


--===========  get_dig_groups   ===============
--returns the groups for digging special gems nodes
gems_battle.get_dig_groups = function(gem_name,soft)
    local groups = {ruby=1,sapphire=1,emerald=1,opal=1}
    if soft then groups = {ruby=2,sapphire=2,emerald=2,opal=2} end
    groups[gem_name] = 3
    return groups
end


--===========  clear_inv   ===============
--clears a player's inventory, including armor. Pass a player objref
gems_battle.clear_inv = function(player)
    local inv = player:get_inventory()
    local list = inv:get_list("main")
    for k, v in pairs(list) do
        inv:remove_item("main", v)
    end
    local elems = armor:get_weared_armor_elements (player)
    if elems then
        armor:remove_all(player)
    end
end


--===========  get_team_id_by_name   ===============

--Gets a team id given a name

function gems_battle.get_team_id_by_name(arena , name)
    for id, stats in pairs( arena.teams ) do
        if stats.name == name then
            return id
        end
    end
    return nil
end

--===========  get_active_team_names   ===============

--returns the list of teams names which are active in this arena

function gems_battle.get_active_team_names(arena)
    local names = {} 
    for id, stats in pairs(arena.teams) do
        table.insert(names, stats.name)
    end
    return names
end

-- returns the translated team name given a team id name
function gems_battle.get_capname(team_name)
    for i,t_name in ipairs(gems_battle.team_names) do
        if t_name == team_name then
            return gems_battle.team_names_caps[i]
        end
    end
end

--===========  Clear Objects   ===============
--clears objects (Game entities) in the area pos1 to pos2

local callback = function(blockpos, action, calls_remaining, param)
    local npos1, npos2 = vector.sort(vector.multiply(blockpos, 16), vector.add(vector.multiply(blockpos, 16), 15))
    local objs = minetest.get_objects_in_area(npos1, npos2)
    for _,obj in pairs(objs) do
        if obj:get_luaentity() ~= nil then
            obj:remove()
        end
    end
end

gems_battle.clearobjects = function(arena)
    -- minetest.debug("Objects removed")
    minetest.emerge_area(arena.pos1, arena.pos2, callback)
end


----- particle effects ----
function gems_battle.make_special_damage_particles(center, team)
    minetest.add_particlespawner({

        amount = 20,          
        time = 1,          
        collisiondetection = true,
        collision_removal = false,
        object_collision = false,
        glow = 3,


        -- legacy defs
        minpos = vector.add(center,vector.new(-.6,0,-.6)),
        maxpos = vector.add(center,vector.new(.6,0,.6)),
        minvel = vector.new(-1,0,-1),
        maxvel = vector.new(1,0,1),
        minacc = vector.new(0,-9.8,0),
        maxacc = vector.new(0,-9.8,0),
        minexptime = 2,
        maxexptime = 2,
        minsize = 1,
        maxsize = 1,

        --modern defs
        texture = {
            name = "gems_particle_"..team..".png",
            alpha_tween = {
                0.0, 1.0,
                style = "pulse",
                reps = 3,
            },
            scale_tween = {
                0.5, 1.0,
                style = "pulse",
                reps = 3,
            },
        },
        drag = 2,
        bounce = .5,
        vel = 0,
        attract = {
            strength = -1.5,
            kind = "plane",
            origin = center,
            direction = vector.new(0,1,0),
            radius = {min = 0.5, max = 1, bias = 1},
        },
    })
end


gems_battle.show_hud_team_location = function( arena, show_to_team_id , show_loc_of_team_id)
    local show_loc_of_team_name = arena.teams[show_loc_of_team_id].name
    local show_of_color = gems_battle.get_color_code(show_loc_of_team_name, false, true)
    local show_to_team_players = arena_lib.get_players_in_team(arena, show_to_team_id)
    local show_loc_of_team_players = arena_lib.get_players_in_team(arena, show_loc_of_team_id)
    for _ , p_name in pairs(show_to_team_players) do
        local player = minetest.get_player_by_name(p_name)
        --t for target
        for _ , t_name in pairs(show_loc_of_team_players) do
            local t_player = minetest.get_player_by_name(t_name)
            if not t_player then return end
            local t_pos = vector.add(t_player:get_pos(),vector.new(0,1,0))
            --add hud
            local idx1 = player:hud_add({
                hud_elem_type = "waypoint",
                name = show_loc_of_team_name.. " player",
                number = show_of_color,
                world_pos = t_pos,
                z_index = 1,
                alignment = 0,
                offset = {x = 0, y = 20},
            })
            local idx2 = player:hud_add({
                hud_elem_type = "image_waypoint",
                text = "gems_loc_"..show_loc_of_team_name ..".png", -- The name of the texture to display.
                world_pos = t_pos, -- World position of the waypoint.
                scale = {x = 2, y = 2}, -- Scale of the image, with {x = 1, y = 1} being the original texture size.
                alignment = 0,
                z_index = 2,
                offset = {x = 0, y = -20},
            })
            minetest.after(10,function(idx,p_name)
                local player = minetest.get_player_by_name(p_name)
                if not player then return end
                player:hud_remove(idx1)
                player:hud_remove(idx2)
            end,idx,p_name)
        end
    end
end




function gems_battle.print_error(pl_name, msg)
    minetest.chat_send_player(pl_name, minetest.colorize("#e6482e", "[gems]" .. msg))
end



function gems_battle.print_msg(pl_name, msg)
    minetest.chat_send_player(pl_name, "[gems]" .. msg)
end



gems_battle.get_currency = function(team)
    local currency = ""
    if team == "ruby" then currency = S("Rubies") end 
    if team == "emerald" then currency = S("Emeralds") end 
    if team == "opal" then currency = S("Opals") end 
    if team == "sapphire" then currency = S("Sapphires") end 

    return currency
end


-- LOCAL FUNCTIONS

function is_one_of(var,tbl)
    for j,k in pairs(tbl) do
        if k == var then
            return true
        end
    end
    return false
end

gems_battle.is_one_of = is_one_of