local _,ns = ...
local dataFrameBuffer = {}
local tableData = {}
local ocultarFrame = nil
local mostrarFrame = nil
local L = ns.L

--[[ --GetNumBankSlots()


--for i = 1, NUM_BAG_SLOTS + NUM_BANKBAGSLOTS do

for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
    bolsas[i]=1
end
for i = NUM_BAG_SLOTS+1, NUM_BAG_SLOTS+NUM_BANKBAGSLOTS do --todas for i = 1, NUM_BAG_SLOTS + NUM_BANKBAGSLOTS do
    local invID = ContainerIDToInventoryID(i)
    print(i, invID, GetInventoryItemLink("player", invID))
    --if not IsInventoryItemProfessionBag("player", invID) then
        print(GetContainerNumFreeSlots(i)) --free slots devuelve el número de slots libres y de segundo argumento el tipo de bolsa, siendo 0 la de meter objetos y un número para otras, te ahorras el isinventoryitemprofesion bag
        --bag types: https://wowwiki-archive.fandom.com/wiki/ItemFamily
    --end
end

print(GetInventoryItemID("player", 52))--banco
print(GetInventoryItemLink("player", 52))--banco
--GetInventoryItemCount("unit",invSlot)
PickupInventoryItem(52) --BANCO
--PickupContainerItem(6,1) --BOLSAS
--PutItemInBag(80) --BANCO Y BOLSA GENÉRICO
IsInventoryItemLocked(52)--para banco, y para bolsas poner getcontaineriteminfo? ]]

--https://wow.gamepedia.com/InventorySlotId
--https://wowwiki-archive.fandom.com/wiki/World_of_Warcraft_API#Cursor
--icon, itemCount, locked = GetContainerItemInfo(bagID, slot)
--SplitContainerItem(bagID,slot,amount)



local function pairsByKeys (t)
    local a = {}
    for n in pairs(t) do
        table.insert(a, n)
    end
    table.sort(a)
    local i = 0      -- iterator variable
    local iter = function ()   -- iterator function
        i = i + 1
        if a[i] == nil then
            return nil
        else
            return a[i], t[a[i]]
        end
    end
    return iter
end



local function getTotalBankFreeSlots() --devuelve 28 si no está el banco abierto
    local total = 0
    for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
        if not GetInventoryItemID("player", i) then
            total = total + 1
        end
    end
    for i = NUM_BAG_SLOTS+1, NUM_BAG_SLOTS+NUM_BANKBAGSLOTS do 
        --local invID = ContainerIDToInventoryID(i)
        --print(i, invID, GetInventoryItemLink("player", invID))
        local num, type = C_Container.GetContainerNumFreeSlots(i)
        if type == 0 then
            total = total + num
        end
    end
    --print(total)
    return total
end

--[[ local start = GetTimePreciseSec() --11ms
for i=1,98*7 do
    getTotalBankFreeSlots()
end
print (GetTimePreciseSec()-start) ]]

local function getNextInventoryItem() --devuelve 28 si no está el banco abierto
    for b = 0, 4 do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            local icon, itemCount, locked = C_Container.GetContainerItemInfo(b, i)
            if not icon then
                return b,i
            end
        end
    end
    return nil,nil
end
--[[ local start = GetTimePreciseSec() -- 900ms
for i=1,98*7 do
    getNextInventoryItem()
end
print (GetTimePreciseSec()-start) ]]

local sitiosLibre = {}
local function InitBankSlots()
    sitiosLibre = { banco = {}, bolsa = {}}
    for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
        if not GetInventoryItemID("player", i) then
            sitiosLibre.banco[i] = 0
        end
    end
    for i = NUM_BAG_SLOTS+1, NUM_BAG_SLOTS+NUM_BANKBAGSLOTS do 
        local invID = C_Container.ContainerIDToInventoryID(i)
        --print(i, invID, GetInventoryItemLink("player", invID))
        local num, type = C_Container.GetContainerNumFreeSlots(i)
        if type == 0 then
            if num > 0 then
                sitiosLibre.bolsa[invID] = num
            end
        end
    end
end

local function getNextBankSlot()
    for k,v in pairsByKeys(sitiosLibre) do
        if k == "banco" then
            for x,y in pairsByKeys (v) do
                sitiosLibre.banco[x] = nil
                return 0,x
            end
        elseif k == "bolsa" then
            for x,y in pairsByKeys (v) do
                if y == 0 then
                    sitiosLibre.bolsa[x] = nil
                else
                    sitiosLibre.bolsa[x] = sitiosLibre.bolsa[x] - 1
                    return x,0
                end
            end
        end
    end
    return nil,nil
end

--[[ local function getNextBankSlot()
    for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
        if not GetInventoryItemID("player", i) then
            return 0,i
        end
    end
    for i = NUM_BAG_SLOTS+1, NUM_BAG_SLOTS+NUM_BANKBAGSLOTS do 
        --local invID = ContainerIDToInventoryID(i)
        --print(i, invID, GetInventoryItemLink("player", invID))
        local num, type = GetContainerNumFreeSlots(i)
        if type == 0 then
            if num > 0 then
                return i,0
            end
        end
    end
    return nil, nil
end ]]

--[[ local start = GetTimePreciseSec() --0.5ms (medio ms)
for i=1,98*7 do
    getNextBankSlot()
end
print (GetTimePreciseSec()-start) ]]

local isItemIDonListSelected = nil

local function moverInventarioABanco(CuantosEnInventario)
    InitBankSlots()
    for b = 0, 4 do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            local icon, itemCount, locked, quality, readable, lootable, itemLink, isFiltered, noValue, itemID = C_Container.GetContainerItemInfo(b, i)
            if icon and itemID and not locked then
                --if dataFrameBuffer[itemID] then print(dataFrameBuffer[itemID].cantidadInventario,itemLink,isItemIDonListSelected(itemID),destino) end
                if dataFrameBuffer[itemID] and isItemIDonListSelected(itemID) and dataFrameBuffer[itemID].cantidadInventario>CuantosEnInventario then
                    local item = Item:CreateFromBagAndSlot(b,i)
                    local location = item:GetItemLocation()
                    local isSoulbound = C_Item.IsBound(location)
                    if isSoulbound~=nil and isSoulbound== false then
                        local destino,num = getNextBankSlot()
                        if destino then
                            dataFrameBuffer[itemID].cantidadInventario = dataFrameBuffer[itemID].cantidadInventario - 1
                            C_Container.PickupContainerItem(b,i)
                            if destino == 0 then
                                PutItemInBag(num)
                            elseif destino > 0 then
                                PutItemInBag(destino)
                            end
                        end
                    end
                end
            end
        end
    end
    ocultarFrame()
    --mostrarFrame()
end

local inventarioSlot = {}
local function initInventarioSlots()
    for b = 0, 4 do
        inventarioSlot[b] = {}
        for i = 1, C_Container.GetContainerNumSlots(b) do
            local itemID = C_Container.GetContainerItemID(b, i)
            if itemID == nil then
                inventarioSlot[b][i]=1
            end
        end
    end
end

local function nextInventarioSlots()
    for b = 0, 4 do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            if inventarioSlot[b][i] then
                inventarioSlot[b][i] = nil
                return b, i
            end
        end
    end
end

local movingItems = false
local function isGuildToInventoryMovingObject()
    return movingItems
end
ns.isGuildToInventoryMovingObject = isGuildToInventoryMovingObject
local function SetGuildToInventoryMovingObject(boolean)
    movingItems = boolean
end
ns.SetGuildToInventoryMovingObject = SetGuildToInventoryMovingObject
local itemsToMove ={}

local function moverBancoAInventario(todos)
    initInventarioSlots()
    itemsToMove ={}
    for k,v in pairs(dataFrameBuffer) do
        if todos then
            dataFrameBuffer[k].limiteInferior = 0
        else
            dataFrameBuffer[k].limiteInferior = dataFrameBuffer[k].cantidadBank - 1
        end
    end

    --[[ for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
        local itemID = GetInventoryItemID("player", i)
        
    end ]]
    for b=1,GetNumGuildBankTabs() do
        local name, icon, isViewable, canDeposit, numWithdrawals, remainingWithdrawals, filtered = GetGuildBankTabInfo(b)
        if isViewable and canDeposit then
            for i=1,98 do --MAX_GUILDBANK_SLOTS_PER_TAB not working with 98 with bagnon
                local itemLink = GetGuildBankItemLink(b,i)
                if itemLink then
                    local item = Item:CreateFromItemLink(itemLink)
                    local itemID = item:GetItemID() --alreadycacheD?
                    if itemID then
                        if dataFrameBuffer[itemID] and isItemIDonListSelected(itemID) and dataFrameBuffer[itemID].cantidadBank>dataFrameBuffer[itemID].limiteInferior then
                            local bolsa,slot = nextInventarioSlots()
                            if bolsa then
                                dataFrameBuffer[itemID].cantidadBank = dataFrameBuffer[itemID].cantidadBank - 1
                                table.insert(itemsToMove,{b,i,bolsa,slot})
                            end
                        end
                    end
                end
            end
        end
    end
    
    ocultarFrame()
    ns.mostrarPanelMoviendo(itemsToMove,false) --true hacia banco
end





local function rellenarBolsasConBasura()
    local espacio,bolsa,slot  = 0,0,0
    for b = 0, 4 do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            local icon, itemCount, locked = C_Container.GetContainerItemInfo(b, i)
            if not icon then
                espacio = espacio +1
                bolsa , slot = b,i
            end
        end
    end
    if espacio > 0 then
        C_Container.SplitContainerItem(0,1,1)
        C_Container.PickupContainerItem(bolsa,slot)
    end
    if espacio > 1 then
        C_Timer.After(50/1000, rellenarBolsasConBasura)
    end
end

--rellenarBolsasConBasura()

local scale = 0.7
local bgoutterframe = CreateFrame("Frame",nil, UIParent)
bgoutterframe:SetSize(510,480)
bgoutterframe:SetPoint("CENTER")
bgoutterframe:SetFrameStrata("HIGH");
bgoutterframe:SetClampedToScreen(true)
bgoutterframe:SetMovable(true);
bgoutterframe:SetResizable(false);
bgoutterframe:EnableMouse(true);
bgoutterframe:SetScript("OnMouseDown",function (self,button) if button=="LeftButton" then bgoutterframe:StartMoving() end end); --StartSizing()
bgoutterframe:SetScript("OnMouseUp",function (self,button) if button=="LeftButton" then bgoutterframe:StopMovingOrSizing()  ns.windowGuildMovedTo(self:GetPoint()) end end);
bgoutterframe:SetToplevel(true)

local bg = CreateFrame("Frame",nil,bgoutterframe)
bg:SetSize((510-30)*(1+scale),(480-30)*(1+scale))
bg:SetPoint("CENTER",bgoutterframe,"CENTER")
bg.tex =bg:CreateTexture(nil, "BACKGROUND")
bg.tex:SetAllPoints(bg)
bg.tex:SetHorizTile(true)
bg.tex:SetVertTile(true)
--bg.tex:SetTexture("Interface\\AddOns\\AutoScrap\\images\\backdrop\\woodbackground", "MIRROR", "MIRROR")
bg.tex:SetTexture("Interface\\AddOns\\AutoScrap\\images\\backdrop\\woodbackground", "REPEAT", "REPEAT")
bg:SetScale(100/(1+scale)/100)


local frame = CreateFrame("Frame", nil, bgoutterframe, "BackdropTemplate")
frame:SetPoint("CENTER",bgoutterframe,"CENTER")
frame:SetSize(510, 480)
--dialog:SetClipsChildren(true)
frame:SetBackdrop({
   -- bgFile = "Interface\\AddOns\\AutoScrap\\images\\test",
    edgeFile = "Interface\\AddOns\\AutoScrap\\images\\backdrop\\backdrop",
    edgeSize = 64,
    tileEdge = true,
--tile = true, --background
--tileSize = 0 --background
    insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
--dialog:SetBackdropBorderColor(225/255, 143/256, 60/255  , 1)
--dialog:SetBackdropColor(1, 1, 1, 1)

frame.spam=ns.Utils.crearFrameConTextura (frame,0,105,366,385,1,"mailpanel")
frame.spam:SetPoint("TOPLEFT",frame,"TOPLEFT",25,-20)
--frame.spam:SetScale(1)
frame.mainTitle=frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
frame.mainTitle:SetText(L["|cFFc5aca8GuildBank to Inventory|r"])
--frame.mainTitle:SetShadowColor(1,1,1,1)
frame.mainTitle:SetPoint("LEFT",frame.spam,"RIGHT",50,-3)

local function setTooltip(parentFrame,...)
    local text1,text2,text3,text4=...
    parentFrame:HookScript("OnEnter", function(self)
        GameTooltip:SetOwner( parentFrame, "ANCHOR_NONE" );
        GameTooltip:SetPoint("TOPLEFT", bgoutterframe, "BOTTOMLEFT", 5, -2)
        if text1 then
        --print(HIGHLIGHT_FONT_COLOR_CODE..text1..FONT_COLOR_CODE_CLOSE)
            GameTooltip:AddLine(NORMAL_FONT_COLOR_CODE..text1..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        if text2 then
            GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..text2..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        if text3 then
            GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..text3..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        if text4 then
            GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..text4..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        --AutoScrapTooltip:AddDoubleLine("prob", "lala")
        GameTooltip:Show()
    end)
    parentFrame:HookScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
end

local destroy = nil
ocultarFrame = function ()
    bgoutterframe:Hide()
    destroy()
end
ns.ocultarGuildToInvFrame = ocultarFrame
local init = nil
mostrarFrame = function()
    init()
    bgoutterframe:ClearAllPoints()
    bgoutterframe:SetPoint(ns.getWindowGuildMovedTo())
    bgoutterframe:Show()
end
ns.mostrarGuildToInvFrame = mostrarFrame
local function toggleFrame()
    if bgoutterframe:IsShown() then
        ocultarFrame()
    else
        mostrarFrame()
    end
end
ns.toggleGuildToInvFrame = toggleFrame


local listItems = CreateFrame("Frame", nil, frame, "BackdropTemplate")
listItems:SetPoint("TOP",frame,"TOP",0,-59)
listItems:SetSize(471, 288)

--dialog:SetClipsChildren(true)
listItems:SetBackdrop({
    bgFile = "Interface\\AddOns\\AutoScrap\\images\\backdrop\\minibackground",
    edgeFile = "Interface\\AddOns\\AutoScrap\\images\\backdrop\\minibackdrop",
    edgeSize = 16,
    tileEdge = true,
--tile = true, --background
--tileSize = 0 --background
    insets = { left = 7, right = 7, top = 6, bottom = 6 },
})

frame.c = CreateFrame("Button", nil, frame)
frame.c:SetNormalTexture(130832) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Up"
frame.c:SetPushedTexture(130830) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Down"
frame.c:SetHighlightTexture(130831) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight"
frame.c:SetSize(32, 32)
frame.c:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -14, -15)
frame.c:SetScript("OnClick", ocultarFrame)

listItems.titlePanel = ns.Utils.crearFrameConTextura (listItems,0,431,493,512,1,"mailpanel")
listItems.titlePanel:SetPoint("BOTTOM",listItems,"TOP",-9,-6)
listItems.frameInv = CreateFrame("Frame",nil,listItems.titlePanel)
listItems.frameiLink = CreateFrame("Frame",nil,listItems.titlePanel)
listItems.frameBank = CreateFrame("Frame",nil,listItems.titlePanel)
listItems.frameAH = CreateFrame("Frame",nil,listItems.titlePanel)
listItems.framePrice = CreateFrame("Frame",nil,listItems.titlePanel)
listItems.titlePanel.tex1= listItems.frameInv:CreateFontString(nil,nil,"GameFontHighlightSmall")
listItems.titlePanel.tex2= listItems.frameiLink :CreateFontString(nil,nil,"GameFontHighlightSmall")
listItems.titlePanel.tex3= listItems.frameBank:CreateFontString(nil,nil,"GameFontHighlightSmall")
listItems.titlePanel.tex4= listItems.frameAH:CreateFontString(nil,nil,"GameFontHighlightSmall")
listItems.titlePanel.tex5= listItems.framePrice:CreateFontString(nil,nil,"GameFontHighlightSmall")
listItems.frameInv:SetPoint("LEFT", listItems.titlePanel, "LEFT", 0, 0)
listItems.frameInv:SetSize(40,12)
listItems.frameiLink:SetPoint("LEFT", listItems.frameInv, "RIGHT", 0, 0)
listItems.frameiLink:SetSize(220,12)
listItems.frameBank:SetPoint("LEFT", listItems.frameiLink, "RIGHT", 0, 0)
listItems.frameBank:SetSize(40,12)
listItems.frameAH:SetPoint("LEFT", listItems.frameBank, "RIGHT", 0, 0)
listItems.frameAH:SetSize(40,12)
listItems.framePrice:SetPoint("LEFT", listItems.frameAH, "RIGHT", 0, 0)
listItems.framePrice:SetSize(90,12)

listItems.titlePanel.tex1:SetText(L["Inv"])
listItems.titlePanel.tex2:SetText(L["Item Name"])
listItems.titlePanel.tex3:SetText(L["Bank"])
listItems.titlePanel.tex4:SetText(L["AH"])
listItems.titlePanel.tex5:SetText(L["Price"])

listItems.titlePanel.tex1:SetPoint("CENTER",listItems.frameInv,"CENTER")
listItems.titlePanel.tex2:SetPoint("CENTER",listItems.frameiLink,"CENTER")
listItems.titlePanel.tex3:SetPoint("CENTER",listItems.frameBank,"CENTER")
listItems.titlePanel.tex4:SetPoint("CENTER",listItems.frameAH,"CENTER")
listItems.titlePanel.tex5:SetPoint("CENTER",listItems.framePrice,"CENTER")

--dialog:SetClipsChildren(true)


local scrollFrame = CreateFrame("ScrollFrame", nil, listItems, "UIPanelScrollFrameTemplate")
scrollFrame:SetPoint("TOPLEFT", listItems, "TOPLEFT", 11, -7)
scrollFrame:SetPoint("BOTTOMRIGHT", listItems, "BOTTOMRIGHT", -30, 6)
--scrollFrame:SetClipsChildren(true) -- poner después de los hijos o no va.

local childScrollFrame = CreateFrame ("Frame",nil,scrollFrame)
childScrollFrame:SetSize(500,12) --adjust
scrollFrame:SetScrollChild(childScrollFrame)




--[[ local row2 = CreateFrame("Frame",nil,childScrollFrame)
row2.frameInv = CreateFrame("Frame",nil,row2)
--row2.frameInv:SetClipsChildren(true)
row2.frameiLink = CreateFrame("Frame",nil,row2)
row2.frameiLink:SetClipsChildren(true)
row2.frameBank = CreateFrame("Frame",nil,row2)
--row2.frameBank:SetClipsChildren(true)
row2.frameAH = CreateFrame("Frame",nil,row2)
--row2.frameBank:SetClipsChildren(true)
row2.framePrice = CreateFrame("Frame",nil,row2)
--row2.frameBank:SetClipsChildren(true)
row2.tex = row2:CreateTexture()
row2.inv = row2:CreateFontString(row2.frameInv,nil,"GameFontHighlight")
row2.iLink = row2:CreateFontString(row2.frameiLink,nil,"GameFontHighlight")
row2.bank = row2:CreateFontString(row2.frameBank,nil,"GameFontHighlight")
row2.AH = row2:CreateFontString(row2.frameAH,nil,"GameFontHighlight")
row2.price = row2:CreateFontString(row2.framePrice,nil,"GameFontHighlight")

row2.inv:SetText("1")
row2.bank:SetText("")
row2.iLink:SetText(""..(GetContainerItemLink(0,2) or "failed"))
row2.AH:SetText("1")
row2.price:SetText("36g")

row2:SetPoint("TOPLEFT", row1, "BOTTOMLEFT", 0, 0)
row2:SetSize(500,row2.iLink:GetHeight()+8)
row2.tex:SetAllPoints(row2)
row2.tex:SetColorTexture(000/255, 000/255, 000/255 , 1)
row2.tex:SetAlpha(0.2)

row2.frameInv:SetPoint("TOPLEFT",row2,"TOPLEFT")
row2.frameInv:SetPoint("BOTTOM",row2,"BOTTOM")
row2.frameInv:SetWidth(40)
row2.inv:SetPoint("CENTER",row2.frameInv,"CENTER")

row2.frameiLink:SetPoint("TOPLEFT",row2.frameInv,"TOPRIGHT")
row2.frameiLink:SetPoint("BOTTOM",row2,"BOTTOM")
row2.frameiLink:SetWidth(220)
row2.iLink:SetPoint("LEFT",row2.frameiLink,"LEFT")

row2.frameiLink:SetPoint("TOPLEFT",row2.frameInv,"TOPRIGHT")
row2.frameiLink:SetPoint("BOTTOM",row2,"BOTTOM")
row2.frameiLink:SetWidth(220)
row2.iLink:SetParent(row2.frameiLink)
row2.iLink:SetPoint("LEFT",row2.frameiLink,"LEFT")

row2.frameBank:SetPoint("TOPLEFT",row2.frameiLink,"TOPRIGHT")
row2.frameBank:SetPoint("BOTTOM",row2,"BOTTOM")
row2.frameBank:SetWidth(40)
row2.bank:SetPoint("CENTER",row2.frameBank,"CENTER")

row2.frameAH:SetPoint("TOPLEFT",row2.frameBank,"TOPRIGHT")
row2.frameAH:SetPoint("BOTTOM",row2,"BOTTOM")
row2.frameAH:SetWidth(40)
row2.AH:SetPoint("CENTER",row2.frameAH,"CENTER")

row2.framePrice:SetPoint("TOPLEFT",row2.frameAH,"TOPRIGHT")
row2.framePrice:SetPoint("BOTTOM",row2,"BOTTOM")
row2.framePrice:SetWidth(90)
row2.price:SetPoint("CENTER",row2.framePrice,"CENTER")

row2:SetScript('OnEnter', function() row2.tex:SetAlpha(0.4) end)
row2:SetScript('OnLeave', function()  row2.tex:SetAlpha(0.2) end)
row2:SetScript('OnMouseDown', function (self,button) if button=="LeftButton" then  row2.tex:SetColorTexture(255/255, 215/255, 0/255 , 1) end end) ]]


local function updateList(itemID,isBank)
    --print(itemID)
    local actualizado = false
    for k,v in ipairs (tableData)do
        if v.row.itemID == itemID and v.live == true then
            actualizado=true
            v.row.inv:SetText(""..dataFrameBuffer[itemID].cantidadInventario)
            v.row.bank:SetText(""..dataFrameBuffer[itemID].cantidadBank)
            --v.bank:SetText("98")
            --v.iLink:SetText("".. dataFrameBuffer[itemID])
            --v.AH:SetText(""..dataFrameBuffer[itemID].cantidadAH)
            --v.price:SetText(dataFrameBuffer[itemID].precio)
        end
    end

    if isBank then -- no pintamos filas con el banco.
        actualizado = true
    end

    if not actualizado then
        -- si no existe la tabla
        local rowNumber = 1
        for k,v in ipairs (tableData)do
            if v.live == false then
                rowNumber=k
                break
            else
                rowNumber = k+1
            end
        end
        --print(rowNumber)
        if not tableData[rowNumber] then
            local row = {}
            --table.insert(tableData,row)
            tableData[rowNumber]=row
            tableData[rowNumber].live = true
            --creation
            if rowNumber==1 then
                tableData[rowNumber].row = CreateFrame("Frame",nil,childScrollFrame)
            else
                tableData[rowNumber].row = CreateFrame("Frame",nil,tableData[rowNumber-1].row)
            end
            tableData[rowNumber].row.frameInv = CreateFrame("Frame",nil,tableData[rowNumber].row)
            tableData[rowNumber].row.frameiLink = CreateFrame("Frame",nil,tableData[rowNumber].row)
            tableData[rowNumber].row.frameBank = CreateFrame("Frame",nil,tableData[rowNumber].row)
            tableData[rowNumber].row.frameAH = CreateFrame("Frame",nil,tableData[rowNumber].row)
            tableData[rowNumber].row.framePrice = CreateFrame("Frame",nil,tableData[rowNumber].row)
            tableData[rowNumber].row.tex = tableData[rowNumber].row:CreateTexture()
            tableData[rowNumber].row.inv = tableData[rowNumber].row:CreateFontString(nil,nil,"GameFontHighlight")
            tableData[rowNumber].row.iLink = tableData[rowNumber].row:CreateFontString(nil,nil,"GameFontHighlight")
            tableData[rowNumber].row.bank = tableData[rowNumber].row:CreateFontString(nil,nil,"GameFontHighlight")
            tableData[rowNumber].row.AH = tableData[rowNumber].row:CreateFontString(nil,nil,"GameFontHighlight")
            tableData[rowNumber].row.price = tableData[rowNumber].row:CreateFontString(nil,nil,"GameFontHighlight")
            --fin creation
        end
        tableData[rowNumber].live = true
        tableData[rowNumber].row:ClearAllPoints()
        tableData[rowNumber].row.selected = false
        tableData[rowNumber].row.itemID= itemID
        if rowNumber % 2 == 0 then
            tableData[rowNumber].row.par =true
        else
            tableData[rowNumber].row.par =false
        end
        tableData[rowNumber].row.frameInv:ClearAllPoints()
        tableData[rowNumber].row.frameiLink:ClearAllPoints()
        tableData[rowNumber].row.frameiLink:SetClipsChildren(true)
        tableData[rowNumber].row.frameBank:ClearAllPoints()
        tableData[rowNumber].row.frameAH:ClearAllPoints()
        tableData[rowNumber].row.framePrice:ClearAllPoints()
        tableData[rowNumber].row.tex:ClearAllPoints()
        tableData[rowNumber].row.inv:ClearAllPoints()
        tableData[rowNumber].row.iLink:ClearAllPoints()
        tableData[rowNumber].row.bank:ClearAllPoints()
        tableData[rowNumber].row.AH:ClearAllPoints()
        tableData[rowNumber].row.price:ClearAllPoints()

        tableData[rowNumber].row.inv:SetText(""..dataFrameBuffer[itemID].cantidadInventario)
        tableData[rowNumber].row.bank:SetText(""..dataFrameBuffer[itemID].cantidadBank)
        tableData[rowNumber].row.iLink:SetText("".. dataFrameBuffer[itemID].itemLink)
        tableData[rowNumber].row.AH:SetText(""..dataFrameBuffer[itemID].cantidadAH)
        tableData[rowNumber].row.price:SetText(dataFrameBuffer[itemID].precio)

        if rowNumber == 1 then
            tableData[rowNumber].row:SetPoint("TOPLEFT", childScrollFrame, "TOPLEFT", 0, 0)
        else
            tableData[rowNumber].row:SetPoint("TOPLEFT", tableData[rowNumber-1].row, "BOTTOMLEFT", 0, 0)
        end
        tableData[rowNumber].row:SetSize(500,tableData[rowNumber].row.iLink:GetHeight()+8)
        tableData[rowNumber].row.tex:SetAllPoints(tableData[rowNumber].row)
        if rowNumber%2 == 1 then
            tableData[rowNumber].row.tex:SetColorTexture(100/255, 100/255, 100/255 , 1)
        else
            tableData[rowNumber].row.tex:SetColorTexture(000/255, 000/255, 000/255 , 1)
        end
        tableData[rowNumber].row.tex:SetAlpha(0.2)

        tableData[rowNumber].row.frameInv:SetPoint("TOPLEFT",tableData[rowNumber].row,"TOPLEFT")
        tableData[rowNumber].row.frameInv:SetPoint("BOTTOM",tableData[rowNumber].row,"BOTTOM")
        tableData[rowNumber].row.frameInv:SetWidth(40)
        tableData[rowNumber].row.inv:SetPoint("CENTER",tableData[rowNumber].row.frameInv,"CENTER")

        tableData[rowNumber].row.frameiLink:SetPoint("TOPLEFT",tableData[rowNumber].row.frameInv,"TOPRIGHT")
        tableData[rowNumber].row.frameiLink:SetPoint("BOTTOM",tableData[rowNumber].row,"BOTTOM")
        tableData[rowNumber].row.frameiLink:SetWidth(220)
        tableData[rowNumber].row.iLink:SetParent(tableData[rowNumber].row.frameiLink)
        tableData[rowNumber].row.iLink:SetPoint("LEFT",tableData[rowNumber].row.frameiLink,"LEFT")

        tableData[rowNumber].row.frameBank:SetPoint("TOPLEFT",tableData[rowNumber].row.frameiLink,"TOPRIGHT")
        tableData[rowNumber].row.frameBank:SetPoint("BOTTOM",tableData[rowNumber].row,"BOTTOM")
        tableData[rowNumber].row.frameBank:SetWidth(40)
        tableData[rowNumber].row.bank:SetPoint("CENTER",tableData[rowNumber].row.frameBank,"CENTER")

        tableData[rowNumber].row.frameAH:SetPoint("TOPLEFT",tableData[rowNumber].row.frameBank,"TOPRIGHT")
        tableData[rowNumber].row.frameAH:SetPoint("BOTTOM",tableData[rowNumber].row,"BOTTOM")
        tableData[rowNumber].row.frameAH:SetWidth(40)
        tableData[rowNumber].row.AH:SetPoint("CENTER",tableData[rowNumber].row.frameAH,"CENTER")

        tableData[rowNumber].row.framePrice:SetPoint("TOPLEFT",tableData[rowNumber].row.frameAH,"TOPRIGHT")
        tableData[rowNumber].row.framePrice:SetPoint("BOTTOM",tableData[rowNumber].row,"BOTTOM")
        tableData[rowNumber].row.framePrice:SetWidth(90)
        tableData[rowNumber].row.price:SetPoint("CENTER",tableData[rowNumber].row.framePrice,"CENTER")

        tableData[rowNumber].row:SetScript('OnEnter', function()
            if tableData[rowNumber].row.selected then
                tableData[rowNumber].row.tex:SetAlpha(1)
            else
                tableData[rowNumber].row.tex:SetAlpha(0.4)
            end
            GameTooltip:SetOwner( tableData[rowNumber].row, "ANCHOR_NONE" );
            GameTooltip:SetPoint("TOPRIGHT", tableData[rowNumber].row, "TOPLEFT", -10, 0)
            GameTooltip:SetHyperlink(dataFrameBuffer[itemID].itemLink);
            GameTooltip:Show()
        end)
        tableData[rowNumber].row:SetScript('OnLeave', function()
            if tableData[rowNumber].row.selected then
                tableData[rowNumber].row.tex:SetAlpha(0.7)
            else
                tableData[rowNumber].row.tex:SetAlpha(0.2)
            end
            GameTooltip:Hide()
        end)
        tableData[rowNumber].row:SetScript('OnMouseDown', function (self,button)
            if button=="LeftButton" then
                if tableData[rowNumber].row.selected then
                    tableData[rowNumber].row.selected = false
                    if tableData[rowNumber].row.par then
                        tableData[rowNumber].row.tex:SetColorTexture(000/255, 000/255, 000/255 , 1)
                    else
                        tableData[rowNumber].row.tex:SetColorTexture(100/255, 100/255, 100/255 , 1)
                    end
                    tableData[rowNumber].row.tex:SetAlpha(0.4)
                else
                    tableData[rowNumber].row.selected = true
                    --tableData[rowNumber].row.tex:SetColorTexture(255/255, 215/255, 0/255 , 1) --amarillo
                    --tableData[rowNumber].row.tex:SetColorTexture(18/255, 175/255, 149/255 , 1) --verde
                    tableData[rowNumber].row.tex:SetColorTexture(4/255, 91/255, 114/255 , 1)
                    tableData[rowNumber].row.tex:SetAlpha(1)
                end
            end
        end)
        tableData[rowNumber].row:Show()
        childScrollFrame:SetSize(500,(tableData[rowNumber].row:GetHeight()*rowNumber)+10)
    end
end

isItemIDonListSelected = function (itemID)
    for k,v in ipairs (tableData)do
        if v.live and v.row.itemID == itemID and v.row.selected then
            return true
        end
    end
    return false
end

local function seleccionarFila(row)
    row.selected = true
    row.tex:SetColorTexture(4/255, 91/255, 114/255 , 1)
    row.tex:SetAlpha(0.7)
end

local function limpiarSeleccionfila(row)
    row.selected = false
    if row.par then
        row.tex:SetColorTexture(000/255, 000/255, 000/255 , 1)
    else
        row.tex:SetColorTexture(100/255, 100/255, 100/255 , 1)
    end
    row.tex:SetAlpha(0.2)
end

local function insertarLinea(itemID,itemLink,cantidadAH,precio,isBank)--isBank ahora es inventario que autocompleta a banco, al reves.
    if not isBank then
        if dataFrameBuffer[itemID] then
            dataFrameBuffer[itemID].cantidadBank = dataFrameBuffer[itemID].cantidadBank + 1
            dataFrameBuffer[itemID].itemLink = itemLink
            dataFrameBuffer[itemID].cantidadAH = cantidadAH
            --dataFrameBuffer[itemID].cantidadInventario = dataFrameBuffer[itemID].cantidadInventario
            if precio then
                dataFrameBuffer[itemID].precio = ""..precio.."|cFFecc012g|r"
            else
                dataFrameBuffer[itemID].precio = ""
            end
        else
            dataFrameBuffer[itemID] = {}
            dataFrameBuffer[itemID].itemLink = itemLink
            dataFrameBuffer[itemID].cantidadBank = 1
            dataFrameBuffer[itemID].cantidadAH = cantidadAH
            dataFrameBuffer[itemID].cantidadInventario = 0
            if precio then
                dataFrameBuffer[itemID].precio = ""..precio.."|cFFecc012g|r"
            else
                dataFrameBuffer[itemID].precio = ""
            end
        end
    else
        if dataFrameBuffer[itemID] then
            dataFrameBuffer[itemID].cantidadInventario = dataFrameBuffer[itemID].cantidadInventario + 1
        else
            dataFrameBuffer[itemID] = {}
            dataFrameBuffer[itemID].cantidadInventario = 1
            dataFrameBuffer[itemID].cantidadBank = 0
        end
    end
    updateList(itemID,isBank)
end
local function continueProtectedBankUno(itemLoc,item)
    item:ContinueOnItemLoad(function()
        local location = item:GetItemLocation()
        local itemLink = C_Item.GetItemLink(location)
        local itemID = C_Item.GetItemID(location)
        local isSoulBind = C_Item.IsBound(itemLoc)
        local isItemLocked = C_Item.IsLocked(itemLoc)
        local itemName, dos, itemQuality, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount,
            itemEquipLoc, itemTexture, sellPrice, classID, subclassID, bindType, expacID, setID, isCraftingReagent
            = GetItemInfo(itemLink)
        if not dos or isSoulBind==nil or not itemID or not itemLink or not classID or isItemLocked==nil then
            --print("error en dato nulo")
        else
            if (classID == 4 or classID == 2) and isSoulBind ~= nil and isSoulBind == false and  isItemLocked~= nil and not isItemLocked then
                local cantidad = TSM_API.GetAuctionQuantity("i:"..itemID)
                local whiteListed = false
                for x,y in pairs (AutoScrap_CharSettings.noVenderList) do --mejor con itemlink? variaciones de items
                    if x == itemID then
                        whiteListed = true
                    end
                end
                if not whiteListed then
                    local valorMercadoComparacion
                    local skip = false
                    if not AutoScrap_CharSettings.usar2Mercados then
                        valorMercadoComparacion = TSM_API.GetCustomPriceValue(AutoScrap_CharSettings.TSM_mercado, "i:" .. itemID)
                        if not valorMercadoComparacion then
                            skip = true
                        end
                    else
                        local valordbmarket = TSM_API.GetCustomPriceValue("dbmarket", "i:" .. itemID)
                        local valordbregionmarketavg = TSM_API.GetCustomPriceValue("dbregionmarketavg", "i:" .. itemID)
                        if not valordbmarket and not valordbregionmarketavg then
                            skip = true
                        elseif not valordbmarket then
                            valorMercadoComparacion = valordbregionmarketavg
                        elseif not valordbregionmarketavg then
                            valorMercadoComparacion = valordbmarket
                        else
                            if  valordbmarket > valordbregionmarketavg  then
                                valorMercadoComparacion = valordbmarket
                            else
                                valorMercadoComparacion = valordbregionmarketavg
                            end
                        end
                    end
                    if not skip then
                        insertarLinea(itemID,itemLink,cantidad, math.floor((valorMercadoComparacion/10000)+0.5),false)
                    else
                        insertarLinea(itemID,itemLink,cantidad,nil,false)
                    end
                end
            end
        end
    end)
end

local function continueProtectedBankDos(item)
    --[[ if not item:IsItemEmpty() then
        item:ContinueOnItemLoad(function()
            local location = item:GetItemLocation()
            local isSoulBind = C_Item.IsBound(location)
            local itemID = C_Item.GetItemID(location)
            local itemLink = C_Item.GetItemLink(location)
            local isItemLocked = C_Item.IsLocked(location)
            local itemName, dos, itemQuality, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount,
        itemEquipLoc, itemTexture, sellPrice, classID, subclassID, bindType, expacID, setID, isCraftingReagent
        = GetItemInfo(itemLink)
            if not dos or isSoulBind==nil or not itemID or not itemLink or not classID or isItemLocked==nil then
                --print("no item data:", itemLink)
            else
                if (classID == 4 or classID == 2) and isSoulBind ~= nil and isSoulBind == false and  isItemLocked~= nil and not isItemLocked then
                    local cantidad = TSM_API.GetAuctionQuantity("i:"..itemID)
                    local whiteListed = false
                    for a,b in pairs (AutoScrap_CharSettings.noVenderList) do --mejor con itemlink? variaciones de items
                        if a == itemID then
                            whiteListed = true
                        end
                    end
                    if not whiteListed then
                        local valorMercadoComparacion
                        local skip = false
                        if not AutoScrap_CharSettings.usar2Mercados then
                            valorMercadoComparacion = TSM_API.GetCustomPriceValue(AutoScrap_CharSettings.TSM_mercado, "i:" .. itemID)
                            if not valorMercadoComparacion then
                                skip = true
                            end
                        else
                            local valordbmarket = TSM_API.GetCustomPriceValue("dbmarket", "i:" .. itemID)
                            local valordbregionmarketavg = TSM_API.GetCustomPriceValue("dbregionmarketavg", "i:" .. itemID)
                            if not valordbmarket then
                                skip = true
                            end
                            if not valordbregionmarketavg then
                                skip = true
                            end
                            if not skip then
                                if  valordbmarket > valordbregionmarketavg  then
                                    valorMercadoComparacion = valordbmarket
                                else
                                    valorMercadoComparacion = valordbregionmarketavg
                                end
                            end
                        end
                        if not skip then
                            insertarLinea(itemID,itemLink,cantidad, math.floor((valorMercadoComparacion/10000)+0.5),false)
                        else
                            insertarLinea(itemID,itemLink,cantidad,nil,false)
                        end
                    end
                end
            end
        end)
    end ]]
    if not item:IsItemEmpty() then
        item:ContinueOnItemLoad(function()
            local itemID = item:GetItemID()
            local itemLink = item:GetItemLink()
            local itemName, dos, itemQuality, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount,
        itemEquipLoc, itemTexture, sellPrice, classID, subclassID, bindType, expacID, setID, isCraftingReagent
        = GetItemInfo(itemLink)
            if not dos or not itemID or not itemLink or not classID then
                print("no item data:", itemLink)
            else
                --if (classID == 4 or classID == 2)then
                if itemStackCount == 1 and not(classID == 1) then
                    local cantidad = TSM_API.GetAuctionQuantity("i:"..itemID)
                    local whiteListed = false
                    for a,b in pairs (AutoScrap_CharSettings.noVenderList) do --mejor con itemlink? variaciones de items
                        if a == itemID then
                            whiteListed = true
                        end
                    end
                    if not whiteListed then
                        local valorMercadoComparacion
                        local skip = false
                        if not AutoScrap_CharSettings.usar2Mercados then
                            valorMercadoComparacion = TSM_API.GetCustomPriceValue(AutoScrap_CharSettings.TSM_mercado, "i:" .. itemID)
                            if not valorMercadoComparacion then
                                skip = true
                            end
                        else
                            local valordbmarket = TSM_API.GetCustomPriceValue("dbmarket", "i:" .. itemID)
                            local valordbregionmarketavg = TSM_API.GetCustomPriceValue("dbregionmarketavg", "i:" .. itemID)
                            if not valordbmarket and not valordbregionmarketavg then
                                skip = true
                            elseif not valordbmarket then
                                valorMercadoComparacion = valordbregionmarketavg
                            elseif not valordbregionmarketavg then
                                valorMercadoComparacion = valordbmarket
                            else
                                if  valordbmarket > valordbregionmarketavg  then
                                    valorMercadoComparacion = valordbmarket
                                else
                                    valorMercadoComparacion = valordbregionmarketavg
                                end
                            end
                        end
                        if not skip then
                            insertarLinea(itemID,itemLink,cantidad, math.floor((valorMercadoComparacion/10000)+0.5),false)
                        else
                            insertarLinea(itemID,itemLink,cantidad,nil,false)
                        end
                    end
                end
            end
        end)
    end
end

local function getBankItems()
    --[[ for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
        local iID = GetInventoryItemID("player", i)
        if  iID then
            local itemLoc = ItemLocation:CreateFromEquipmentSlot(i)
            local item = Item:CreateFromItemLocation(itemLoc)
            continueProtectedBankUno(itemLoc,item)
        end
    end
    for i = NUM_BAG_SLOTS+1, NUM_BAG_SLOTS+NUM_BANKBAGSLOTS do 
        --local invID = ContainerIDToInventoryID(i)
        --print(i, invID, GetInventoryItemLink("player", invID))
        local num, type = GetContainerNumFreeSlots(i)
        if type == 0 then
            for x = 1, GetContainerNumSlots(i) do
                local item = Item:CreateFromBagAndSlot(i, x)
                    continueProtectedBankDos(item)
            end
        end
    end ]]
    for b=1,GetNumGuildBankTabs() do
        for i=1,98 do --MAX_GUILDBANK_SLOTS_PER_TAB no existe con bagnon
            local icon, itemCount, locked, isFiltered, quality = GetGuildBankItemInfo(b,i)
            if icon and locked == false then
                local itemLink = GetGuildBankItemLink(b,i)
                local item = Item:CreateFromItemLink(itemLink)
                continueProtectedBankDos(item)
            end
        end
    end
end

local function inventoryProtected(item)
    if not item:IsItemEmpty() then
        item:ContinueOnItemLoad(function()
            local location = item:GetItemLocation()
            local isSoulbound = C_Item.IsBound(location)
            local itemID = C_Item.GetItemID(location)
            local isItemLocked = C_Item.IsLocked(location)--C_Item.IsItemLocked()
            if isSoulbound==nil or not itemID or isItemLocked==nil then
                --print("no item data: ")
            else
                if isSoulbound == false and isItemLocked == false then
                    insertarLinea (itemID,nil,nil,nil,true)
                end
            end
        end)
    end
end

local function getInventoryItems()
    for b = 0, 4 do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            local item = Item:CreateFromBagAndSlot(b, i)
            inventoryProtected(item)
        end
    end
end

init = function()
    dataFrameBuffer = {}
    getBankItems()
    getInventoryItems()
end

destroy =function ()
    for k,v in ipairs (tableData)do
        v.live = false
        v.row:Hide()
    end
    childScrollFrame:SetSize(500,12)
end

local function seleccionarTodo()
    for k,v in ipairs (tableData)do
        if v.live == true then
            seleccionarFila(v.row)
        end
    end
end

local function quitarSeleccion()
    for k,v in ipairs (tableData)do
        if v.live == true then
            limpiarSeleccionfila(v.row)
        end
    end
end

local function seleccionarNotInAH()
    for k,v in ipairs (tableData)do
        if v.live == true and dataFrameBuffer[v.row.itemID].cantidadAH == 0 then
            seleccionarFila(v.row)
        end
    end
end

local selectAll = ns.Utils.crearBoton(frame,150,22,L["Select All"],seleccionarTodo)
selectAll:SetPoint("TOPLEFT", listItems, "BOTTOMLEFT", 20, -5)
local selectinAH = ns.Utils.crearBoton(frame,150,22,L["Select NOT in AH"],seleccionarNotInAH)
selectinAH:SetPoint("TOPLEFT", selectAll, "BOTTOMLEFT", 0, -5)
local moveAllExAH = ns.Utils.crearBoton(frame,140,35,L["Move 1 unit"],function () moverBancoAInventario(false) end)
moveAllExAH:SetPoint("BOTTOM", frame, "BOTTOM", -75, 25)
local moveAll = ns.Utils.crearBoton(frame,140,35,L["Move All"],function () moverBancoAInventario(true) end)
moveAll:SetPoint("BOTTOM", frame, "BOTTOM", 75, 25)
local clearSelection = ns.Utils.crearBoton(frame,150,22,L["Clear Selection"],quitarSeleccion)
clearSelection:SetPoint("TOPRIGHT", listItems, "BOTTOMRIGHT", -20, -5)

local function refreshData()
    ocultarFrame()
    mostrarFrame()
end
ns.refreshDataGuildToInv = refreshData
local function isFrameShown()
    return bgoutterframe:IsShown()
end
ns.isGuildToInvShown = isFrameShown

ocultarFrame()

setTooltip(selectAll,L["Select All"],L["Select all the items in the list"])
setTooltip(selectinAH,L["Select NOT in AH"],L["Select only the items that you DO NOT have in the Auction House."], L["Items in Auction House are cached by TSM, make sure you opened the auction house last time with it."])
setTooltip(moveAllExAH,L["Move 1 unit"],L["If you have multiple copys of an Item on your bank, it will move 1 to your inventory and keep the rest of the selection in the Bank."])
setTooltip(moveAll,L["Move All"],L["Move all items selected to the Inventory."])
setTooltip(clearSelection,L["Clear Selection"],L["Clear all selected items, so you can select them again."],L["It won't delete or move any item, only clear the selected items from list."])