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

local framew, frameh, scale = 300,173, 1.4
local bgoutterframe = CreateFrame("Frame",nil, UIParent)
bgoutterframe:SetSize(framew,frameh)
bgoutterframe:SetPoint("CENTER")
bgoutterframe:SetFrameStrata("DIALOG");

local bg = CreateFrame("Frame",nil,bgoutterframe)
bg:SetSize((framew-15)*(1+scale),(frameh-15)*(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", "REPEAT", "REPEAT")
bg:SetScale(100/(1+scale)/100)


local AutoScrapAlertBox = CreateFrame("Frame", nil, bgoutterframe, "BackdropTemplate")
AutoScrapAlertBox:SetPoint("CENTER",bgoutterframe,"CENTER")
AutoScrapAlertBox:SetSize(framew, frameh    )
--dialog:SetClipsChildren(true)
AutoScrapAlertBox: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 },
})

AutoScrapAlertBox.spam=ns.Utils.crearFrameConTextura (AutoScrapAlertBox,0,105,366,385,1,"mailpanel")
AutoScrapAlertBox.spam:SetPoint("TOPLEFT",AutoScrapAlertBox,"TOPLEFT",31    ,-27)
AutoScrapAlertBox.spam:SetScale(0.80)

local texto = AutoScrapAlertBox:CreateFontString(nil,nil,"GameFontHighlightLarge")
texto:SetPoint("TOP",AutoScrapAlertBox,"TOP",0,-43)

local textoInfo = AutoScrapAlertBox:CreateFontString(nil,nil,"GameFontNormal")
textoInfo:SetPoint("TOPLEFT",AutoScrapAlertBox,"TOPLEFT",34,-53)
textoInfo:SetPoint("BOTTOMRIGHT",AutoScrapAlertBox,"BOTTOMRIGHT",-30,29)
textoInfo:SetText(L["Items are being moved. Don't click anything, just wait!!. Don't touch your Inventory or your GuildBank Frame untill it finish."])

bgoutterframe:Hide()

local totalAMover, movidos
local abort = nil
local itemsToMove = nil

local function ponerTextoMovidos()
    texto:SetText(L["Items moved: "]..movidos.."/"..totalAMover)
end



local function siguienteAMover()
    if itemsToMove then
        for k,v in pairs(itemsToMove) do
        return v[1],v[2],v[3],v[4]
        end
    end
end

local function eliminarItem(a,b,c,d)
    for k,v in pairs(itemsToMove) do
        if v[1]==a and v[2]==b and v[3]==c and v[4]==d then
            itemsToMove[k]=nil
            movidos = movidos + 1
            ponerTextoMovidos(movidos,totalAMover)
        end
    end
end

local lastItemMovedTime = 0
local keepTimerRunning = false
local function MoverItems()
    local bag,slot,tab,index = siguienteAMover()
    if bag == nil then
        keepTimerRunning = false
        lastItemMovedTime = 0
        --print("terminado de mover todos los items")
        ns.SetInventoryToGuildMovingObject(true) --da igual al abrir lo hará
        ns.SetGuildToInventoryMovingObject(true)
        bgoutterframe:Hide()
        --ns.mostrarCartelGuild2botones()
        CloseGuildBankFrame()
        return
    end
    --local icon, itemCount, locked, quality, readable, lootable, itemLink = C_Container.GetContainerItemInfo(bag, slot)
    local tablaItemInfo = C_Container.GetContainerItemInfo(bag, slot)
    local icon = tablaItemInfo and tablaItemInfo["iconFileID"]
    local locked = tablaItemInfo and tablaItemInfo["locked"]

    

    --local icong, _, lockedg = GetGuildBankItemInfo(tab,slot) --secreto?
    local icong, _, lockedg = GetGuildBankItemInfo(tab,index)
    if icon == nil and locked== nil and icong and lockedg == false then
        --print("item movido con éxito: ",bag,slot,tab,index)
        eliminarItem(bag,slot,tab,index)
        lastItemMovedTime= GetTime() - (850/1000) --forzar mover siguiente antes de 1s -- antes era 0, pero si lo ajustas a 150 de la llegada va mejor
    elseif bag then
        if GetTime()-lastItemMovedTime>1000/1000 then
            keepTimerRunning = true
            --print("moviendo item: ",bag,slot,tab,index)
            SetCurrentGuildBankTab(tab)
            ClearCursor()
            C_Container.PickupContainerItem(bag,slot)
            PickupGuildBankItem(tab,index)
            --ClearCursor()
            lastItemMovedTime=GetTime()

            --experimental
            --eliminarItem(bag,slot,tab,index)
        else
            --print("no haciendo nada, sólo comprobando",icon,locked,icong,lockedg)
            --print("objeto:",itemLink, bag, slot, tab, index)
            --print(GetTime())
        end

    end
    if keepTimerRunning then
        C_Timer.After(20/1000,MoverItems)
    end
end

local function moverItemsAInv()--el más bugeado
    local tab,index,bolsa,slot = siguienteAMover()
    --print(tab,index,bolsa)
    if tab == nil then
        keepTimerRunning = false
        lastItemMovedTime = 0
        --print("terminado de mover todos los items")
        ns.SetInventoryToGuildMovingObject(true) --da igual al abrir lo hará
        ns.SetGuildToInventoryMovingObject(true)
        bgoutterframe:Hide()
        --ns.mostrarCartelGuild2botones()
        CloseGuildBankFrame()
        return
    end
    --local icon, itemCount, locked, quality, readable, lootable, itemLink = C_Container.GetContainerItemInfo(bolsa, slot)
    local tablaItemInfo = C_Container.GetContainerItemInfo(bolsa, slot)
    local icon = tablaItemInfo and tablaItemInfo["iconFileID"]
    local locked = tablaItemInfo and tablaItemInfo["locked"]

    local icong, _, lockedg = GetGuildBankItemInfo(tab,index)
    --print("status:", icong, lockedg, icon, locked)
    if icong==nil and lockedg == false and icon and locked ~= true then
        --print("item movido con éxito: ",tab,index,bolsa,slot)
        eliminarItem(tab,index,bolsa,slot)
        lastItemMovedTime= GetTime() - (850/1000) --forzar mover siguiente antes de 1s -- antes era 0, pero si lo ajustas a 150 de la llegada va mejor
    elseif tab then
        if GetTime()-lastItemMovedTime>1000/1000 then
            keepTimerRunning = true
            --print("moviendo item: ",tab,index,bolsa,slot)
            SetCurrentGuildBankTab(tab)
            ClearCursor()
            PickupGuildBankItem(tab,index)
            C_Container.PickupContainerItem(bolsa,slot)


            
            --ClearCursor()
            lastItemMovedTime=GetTime()

            --experimental
            --eliminarItem(bag,slot,tab,index)
        else
            --print("no haciendo nada, sólo comprobando",icong,lockedg)
            --print("objeto:",itemLink, bag, slot, tab, index)
            --print(GetTime())
        end

    end
    if keepTimerRunning then
        C_Timer.After(20/1000,moverItemsAInv)
    end
end

local function mostrarPanelMoviendo(tabla,haciabanco)
    ns.SetInventoryToGuildMovingObject(true)
    ns.SetGuildToInventoryMovingObject(true)
    itemsToMove = tabla
    lastItemMovedTime = 0
    ns.ocultarCartelGuild2botones()
    bgoutterframe:Show()
    if tabla == nil then
        abort()
    end
    local total = 0
    for k,v in pairs(tabla) do
        total = total +1
    end
    totalAMover = total
    movidos = 0
    ponerTextoMovidos(movidos,totalAMover)
    if haciabanco then
        MoverItems()
    else
        moverItemsAInv()
    end
end
ns.mostrarPanelMoviendo = mostrarPanelMoviendo

abort = function()
    keepTimerRunning = false
    itemsToMove = nil
    --ns.ocultarCartelGuild2botones() --se usa en diversos sitios, como cerra al salir corriendo, no se puede mostrar.
    bgoutterframe:Hide()
    ns.SetInventoryToGuildMovingObject(false) --no quitar. estaba en ASguildbank.lua para al arrancar en caso de que quedara pillado al cerrar y abrir reset, en línea 86.
    ns.SetGuildToInventoryMovingObject(false)
    lastItemMovedTime = 0
end
ns.abortMovingObjects = abort

local abortButton = ns.Utils.crearBoton(AutoScrapAlertBox,100,20,L["Abort"],abort)
abortButton:SetPoint("BOTTOM", AutoScrapAlertBox, "BOTTOM", 0, 22)