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

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 num, type = C_Container.GetContainerNumFreeSlots(i)
        if type == 0 then
            total = total + num
        end
    end
    --print(total)
    return total
end


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 sitiosLibre = {}
local function InitBankSlots()
    sitiosLibre = {}
    for b=1,GetNumGuildBankTabs() do
        sitiosLibre[b]={}
        for i=1,98 do --MAX_GUILDBANK_SLOTS_PER_TAB not working with 98 with bagnon
            local name, icon, isViewable, canDeposit, numWithdrawals, remainingWithdrawals, filtered = GetGuildBankTabInfo(b)
            if isViewable and canDeposit then
                local iconItem, itemCount, locked, isFiltered, quality = GetGuildBankItemInfo(b,i)
                if not iconItem then
                    sitiosLibre[b][i]=1
                end
            end
        end
    end
end

local function getNextBankSlot()
    for b=1,GetNumGuildBankTabs() do
        for i=1,98 do --MAX_GUILDBANK_SLOTS_PER_TAB not working with 98 with bagnon
            if sitiosLibre[b][i] then
                sitiosLibre[b][i] = nil
                return b, i
            end
        end
    end
end

local movingItems = false
local function isInventoryToGuildMovingObject()
    return movingItems
end
ns.isInventoryToGuildMovingObject = isInventoryToGuildMovingObject
local function SetInventoryToGuildMovingObject(boolean)
    movingItems = boolean
end
ns.SetInventoryToGuildMovingObject = SetInventoryToGuildMovingObject
local itemsToMove ={}


local isItemIDonListSelected = nil
local function moverInventarioABanco(CuantosEnInventario)
    InitBankSlots()
    itemsToMove ={}
    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)
            local tablaItemInfo = C_Container.GetContainerItemInfo(b, i)
            if tablaItemInfo then
                local icon, locked, itemID = tablaItemInfo["iconFileID"],tablaItemInfo["isLocked"],tablaItemInfo["itemID"]

                if icon and itemID and locked~=nil 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 tab,slot = getNextBankSlot()
                            if tab and slot then
                                dataFrameBuffer[itemID].cantidadInventario = dataFrameBuffer[itemID].cantidadInventario - 1
                                --[[ ClearCursor()
                                C_Container.PickupContainerItem(b,i)
                                PickupGuildBankItem(tab, slot) ]]
                                table.insert(itemsToMove,{b,i,tab,slot})
                            end
                        end
                    end
                end
            end
        end
    end
    ocultarFrame()
    ns.mostrarPanelMoviendo(itemsToMove,true) --true hacia banco
    --mostrarFrame()
end

local inventarioSlot = {}
local function initInventarioSlots()
    inventarioSlot[0] = C_Container.GetContainerNumFreeSlots(0)
    for i = 1, NUM_BAG_SLOTS do
        local invID = C_Container.ContainerIDToInventoryID(i)
        local espacio, tipo = C_Container.GetContainerNumFreeSlots(i)
        if tipo == 0 then
            inventarioSlot[invID] = espacio
        else
            inventarioSlot[invID] = 0
        end
    end
end

local function nextInventarioSlots()
    for k,v in pairsByKeys (inventarioSlot) do
        if k == 0 then
            if v == 0 then
                inventarioSlot[0]=nil
            else
                inventarioSlot[0]=inventarioSlot[0]-1
                return 0
            end
        elseif k>0 then
            if v == 0 then
                inventarioSlot[k]=nil
            else
                inventarioSlot[k]=inventarioSlot[k]-1
                return k
            end
        end
    end
end

local function moverBancoAInventario()
    initInventarioSlots()
    for i=BankButtonIDToInvSlotID(1),BankButtonIDToInvSlotID(1)+NUM_BANKGENERIC_SLOTS-1 do --52,79
        if GetInventoryItemID("player", i) then
            local bolsa = nextInventarioSlots()
            if bolsa then
                if bolsa == 0 then
                    PickupInventoryItem(i)
                    PutItemInBackpack()
                else
                    PickupInventoryItem(i)
                    PutItemInBag(bolsa)
                end
            end
        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
            for x=1, C_Container.GetContainerNumSlots(i) do
                local icon, itemCount, locked = C_Container.GetContainerItemInfo(i, x)
                if icon then
                    local bolsa = nextInventarioSlots()
                    if bolsa then
                        if bolsa == 0 then
                            C_Container.PickupContainerItem(i,x)
                            PutItemInBackpack()
                        else
                            C_Container.PickupContainerItem(i,x)
                            PutItemInBag(bolsa)
                        end
                    end
                end
            end
        end
    end
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["|cFFc5aca8Inventory to GuildBank|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.ocultarGuildFrame = ocultarFrame
local init = nil
mostrarFrame = function()
    init()
    bgoutterframe:ClearAllPoints()
    bgoutterframe:SetPoint(ns.getWindowGuildMovedTo())
    bgoutterframe:Show()
    SetInventoryToGuildMovingObject(false)
end
ns.mostrarGuildFrame = mostrarFrame
local function toggleFrame()
    if bgoutterframe:IsShown() then
        ocultarFrame()
    else
        mostrarFrame()
    end
end
ns.toggleGuildFrame = 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 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)
    if not isBank then
        if dataFrameBuffer[itemID] then
            dataFrameBuffer[itemID].cantidadInventario = dataFrameBuffer[itemID].cantidadInventario + 1
            dataFrameBuffer[itemID].itemLink = itemLink
            dataFrameBuffer[itemID].cantidadAH = cantidadAH
            --dataFrameBuffer[itemID].cantidadBank = dataFrameBuffer[itemID].cantidadBank
            if precio then
                dataFrameBuffer[itemID].precio = ""..precio.."|cFFecc012g|r"
            else
                dataFrameBuffer[itemID].precio = ""
            end
        else
            dataFrameBuffer[itemID] = {}
            dataFrameBuffer[itemID].itemLink = itemLink
            dataFrameBuffer[itemID].cantidadInventario = 1
            dataFrameBuffer[itemID].cantidadAH = cantidadAH
            dataFrameBuffer[itemID].cantidadBank = 0
            if precio then
                dataFrameBuffer[itemID].precio = ""..precio.."|cFFecc012g|r"
            else
                dataFrameBuffer[itemID].precio = ""
            end
        end
    else
        if dataFrameBuffer[itemID] then
            dataFrameBuffer[itemID].cantidadBank = dataFrameBuffer[itemID].cantidadBank + 1
        else
            dataFrameBuffer[itemID] = {}
            dataFrameBuffer[itemID].cantidadBank = 1
            dataFrameBuffer[itemID].cantidadInventario = 0
        end
    end
    updateList(itemID,isBank)
end

local function continueProtectedBankUno(itemLoc,item)
    item:ContinueOnItemLoad(function()
        local location = item:GetItemLocation()
        local itemID = C_Item.GetItemID(location)
        local isSoulBind = C_Item.IsBound(itemLoc)
        local isItemLocked = C_Item.IsLocked(itemLoc)
        if isSoulBind == nil or not itemID or isItemLocked==nil then
            --print("isSouldBind o isItemLocked es un valor nulo")
        end
        if isSoulBind ~= nil and isSoulBind == false and  isItemLocked~= nil and not isItemLocked then
            insertarLinea (itemID,nil,nil,nil,true)
        end
    end)
end

local function continueProtectedBankDos(item)
    if not item:IsItemEmpty() then
        item:ContinueOnItemLoad(function()
            local itemID = item:GetItemID()
            local itemLink = item:GetItemLink()
            --print("dentro:",itemID, itemLink)
            insertarLinea (itemID,nil,nil,nil,true)
        end)
    end
end


local function getBankItems()
    for b=1,GetNumGuildBankTabs() do
        for i=1,98 do --MAX_GUILDBANK_SLOTS_PER_TAB no sale con bagnon abierto.
            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 itemLink = C_Item.GetItemLink(location)
            local itemID = C_Item.GetItemID(location)
            local isItemLocked = C_Item.IsLocked(location)--C_Item.IsItemLocked()
            local itemName, dos, itemQuality, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount,
            itemEquipLoc, itemTexture, sellPrice, classID, subclassID, bindType, expacID, setID, isCraftingReagent
            = GetItemInfo(itemLink)
            if not dos or isSoulbound==nil or not itemLink or not itemID or not classID or isItemLocked==nil then
                --print("no item data: ", itemLink)
            else
                --if (classID == 4 or classID == 2) and isSoulbound == false and isItemLocked == false then
                if itemStackCount == 1 and not(classID == 1) and isSoulbound == false and isItemLocked == false 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
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 = {}
    getInventoryItems()
    getBankItems()
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 seleccionarInAH()
    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,130,22,L["Select All"],seleccionarTodo)
selectAll:SetPoint("TOPLEFT", listItems, "BOTTOMLEFT", 20, -5)
local selectinAH = ns.Utils.crearBoton(frame,130,22,L["Select in AH"],seleccionarInAH)
selectinAH:SetPoint("TOPLEFT", selectAll, "BOTTOMLEFT", 0, -5)
local moveAllExAH = ns.Utils.crearBoton(frame,150,35,L["Move All except 1"],function () moverInventarioABanco(1) end)
moveAllExAH:SetPoint("BOTTOM", frame, "BOTTOM", -75, 25)
local moveAll = ns.Utils.crearBoton(frame,150,35,L["Move All"],function () moverInventarioABanco(0) end)
moveAll:SetPoint("BOTTOM", frame, "BOTTOM", 80, 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.refreshDataInvToGuild = refreshData
local function isFrameShown()
    return bgoutterframe:IsShown()
end
ns.isInvToGuildShown = isFrameShown

ocultarFrame()

setTooltip(selectAll,L["Select All"],L["Select all the items in the list"])
setTooltip(selectinAH,L["Select in AH"],L["Select only the items that you already 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 All except 1"],L["If you have multiple copys of an Item on your inventory, it will keep 1 and move the rest of the selection to the Bank."], L["If you have only 1 copy, It won't be moved."])
setTooltip(moveAll,L["Move All"],L["Move all items selected to the Bank."])
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."])