local _,ns = ...
local L = ns.L

local bags = {}

local maxPlayers = 4
local currentPlayers = 0
local maxTimeOutInSeconds = 150
local function nuevaTablaSender(sender)
    if currentPlayers < maxPlayers then
        --print ("Creado bag de nuevo jugador")
        ns.addNewPlayer(sender)
        currentPlayers = currentPlayers + 1
        return {items = {}, lastTick = nil, joined = GetTime()}
    end
end

function ns.checkNoResponseAfterLongPeriodOfTime()
    for k,v in pairs (bags) do
        if GetTime() - v.lastTick >= maxTimeOutInSeconds then
            ns.removePlayer(k)
        end
    end
end

function ns.reanudarCombatFrameParado()
    for k,v in pairs (bags) do
        local tempLastTick = v.lastTick
        local tempJoined = v.joined
        bags[k]={items = {}, lastTick = tempLastTick, joined =  tempJoined}
    end
end

function ns.removePlayer(sender)
    if bags[sender] then
        if bags[sender].items then
            bags[sender].items={}
        end
        bags[sender] = nil
        currentPlayers = currentPlayers - 1
        --print ("Bag de", sender, "eliminado")
        ns.removePlayerFromCombatFrame(sender)
    end
end

function ns.removeAllPlayers() -- elimina todos los jugadores de la cache dese el party.lua. también llama a una funcion similar a combat frame, no hace falta rellamar aquí.
    bags = {}
    currentPlayers = 0
end

function ns.AddSenderItem(itemID, cantidad, sender)
    if not bags[sender] then --recibiendo un item antes de que llegara el tk mk d p
        bags[sender] = nuevaTablaSender(sender)
    end
    if bags[sender] then
        if not bags[sender].items[itemID] then
            bags[sender].items[itemID] = cantidad -- después cambiar cantidad por {cantidad,calidad}
            if ns.isCombatShown() then
                ns.senderHasNewItem (sender, itemID, cantidad)
            end
        else
            local tempCantidad = bags[sender].items[itemID] + cantidad
            bags[sender].items[itemID] = tempCantidad
            if ns.isCombatShown() then
                ns.senderHasNewItem (sender, itemID, tempCantidad)
            end
        end
        bags[sender].lastTick= GetTime()
    end
end

function ns.AddSendertkmkdp(mk, d, p, b, sender)
    --print (mk,d,p)
    if not bags[sender] then
        bags[sender] = nuevaTablaSender(sender)
    end

    if bags[sender] then
        bags[sender].lastTick= GetTime()
        if ns.getTimerRunning() then
            if not bags[sender].totalMyKills then --sea el valor que sea metemos 0 la primera vez, por si acabamos de unirnos y nos llega 5.
                --print ("mk por primera vez en", sender)
                --bags[sender].initMyKills = mk
                bags[sender].totalMyKills = 0
                bags[sender].totalGold = 0
                bags[sender].totalPlants = 0
                bags[sender].porcentajeBolsaLlena = b
                if ns.isCombatShown() then
                    ns.setPlayerKPD(sender,0,0,0)
                    ns.senderHasNewBagPercentage(sender,b)
                end
            else
                --print ("mk",mk, "totalmk", bags[sender].totalMyKills, "p", p, "tp",bags[sender].initPlants, "d",d, "td",bags[sender].totalGold)
                --print (mk, bags[sender].totalMyKills, type(mk))
                if mk > 0 or p > 0 or d~= 0 then
                    local tk,td,tp
                    tk = bags[sender].totalMyKills + mk
                    bags[sender].totalMyKills = tk
                    td = bags[sender].totalGold + d
                    bags[sender].totalGold = td
                    tp = bags[sender].totalPlants + p
                    bags[sender].totalPlants = tp
                    --print (mk, bags[sender].totalMyKills)
                    if ns.isCombatShown() then
                        ns.setPlayerKPD(sender,tk,tp,math.floor(td/10000))
                    end
                else
                    --print ("data from", sender, "not valid TK MK D P < initData")
                    --[[ bags[sender].initMyKills = mk
                    bags[sender].initPlants = p
                    bags[sender].initGold = -(bags[sender].totalGold) ]]
                    --ns.removePlayer(sender)
                end
                bags[sender].porcentajeBolsaLlena = b
                if ns.isCombatShown() then
                    ns.senderHasNewBagPercentage(sender,b)
                end
            end
        end
    end
end

function ns.getPorcentajeBolsaLlena(sender)
    if bags[sender] then
       return bags[sender].porcentajeBolsaLlena
    end
end

function ns.getAllDataFromName(name)
    if bags[name] and bags[name].totalMyKills then
        return bags[name].totalMyKills, bags[name].totalPlants, bags[name].totalGold
    end
end

function ns.getItemDataFromName(name, itemID)
    if bags[name] and bags[name].items then
        return bags[name].items[itemID]
    end
end

function ns.getPartyInventoryMax()
    local max, name = 0,  ""
    for k,v in pairs (bags) do
        if v.porcentajeBolsaLlena and v.porcentajeBolsaLlena >= max then
            max = v.porcentajeBolsaLlena
            name = k
        end
    end
    return max, name
end
