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

local pressedFunc
local frameSellingInventory
local startAutoSelling

--[[ local function setTooltip(parentFrame,...)
    local text1,text2,text3,text4=...
    parentFrame:HookScript("OnEnter", function(self)
        GameTooltip:SetOwner( parentFrame, "ANCHOR_NONE" );
        GameTooltip:SetPoint("BOTTOMLEFT", MerchantFrame, "BOTTOMRIGHT", 0, 0)
        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 function sellBlizzardJunk()
    if C_MerchantFrame.GetNumJunkItems() > 0 then
        C_MerchantFrame.SellAllJunkItems()
    end
end

local function crearBotonMerchantFrame()
    local frame = CreateFrame ("Frame", nil, MerchantBuyBackItem)
    frame:SetSize(40,40)
    frame.tex = frame:CreateTexture()
    frame.tex:SetTexture("Interface\\AddOns\\AutoScrap\\images\\mailpanel")
    frame.tex:SetTexCoord(0/512, 40/512, 67/512 , (67+40)/512)
    frame.tex:SetAllPoints(frame)

    frame.enterTex = frame:CreateTexture()
    frame.enterTex:SetTexture("Interface\\AddOns\\AutoScrap\\images\\mailpanel")
    frame.enterTex:SetTexCoord(40/512, 80/512, 67/512 , (67+40)/512)
    frame.enterTex:SetAllPoints(frame)
    frame.enterTex:Hide()

    frame.pressedTex = frame:CreateTexture()
    frame.pressedTex:SetTexture("Interface\\AddOns\\AutoScrap\\images\\mailpanel")
    frame.pressedTex:SetTexCoord(80/512, 120/512, 67/512 , (67+40)/512)
    frame.pressedTex:SetAllPoints(frame)
    frame.pressedTex:Hide()

    local pressed = false
    frame:SetScript("OnEnter",function (self,motion)
        --if motion then
            if pressed then
                frame.pressedTex:Show()
            end
            frame.enterTex:Show()
        --end
    end)
    frame:SetScript("OnLeave",function (self,motion)
        --if motion then
            frame.pressedTex:Hide()
            frame.enterTex:Hide()
        --end
    end)
    frame:SetScript("OnHide",function (self,...)
        frame.pressedTex:Hide()
        frame.enterTex:Hide()
        pressed = false
    end)
    frame:SetScript('OnMouseDown', function (self,button)
        if button=="LeftButton" then
            frame.pressedTex:Show()
            frame.enterTex:Show()
            pressed = true
        end
    end)
    frame:SetScript('OnMouseUp', function (self,button)
        if button=="LeftButton" then
            frame.pressedTex:Hide()
            frame.enterTex:Show()
            --if GetMouseFocus()==self then --este código ya no existe en 11.1.0
            if self:IsMouseOver() then
                if AutoScrap_CharSettings.blizzardDefaultJunk then
                    sellBlizzardJunk()
                end
                pressedFunc(true)
                -- no me gusta por el hecho del spam, y que añada cosas mientras da al boton y tal. se podría arreglar
                --startAutoSelling()
            end
            pressed = false
        end
    end)

    return frame
end

local sellingButton = crearBotonMerchantFrame()
sellingButton:Hide()

local function repositionButtons()
    sellingButton:Hide()
    sellingButton:ClearAllPoints()

    -- -- Patch 11.1.0 esto no funciona porque el botón siempre acaba de alguna forma poniendose en Hide. Cambio este código por un hook a OnShow abajo.
    -- if MerchantSellAllJunkButton:IsShown() then
    --     print("el botón estaba visible y lo quito",MerchantFrame:IsShown(),CanMerchantRepair())
    --     MerchantSellAllJunkButton:Hide()

    --print("shows: ", CanMerchantRepair(), CanGuildBankRepair(), MerchantFrame:IsShown()) --usar can repair en lugar de isshown porque a veces los botones todavía no están, pero canrepair dice lo correcto.
    if MerchantFrame:IsShown() then
        if CanMerchantRepair() and CanGuildBankRepair() then --default BOTTOMRIGHT,MerchantFrame,BOTTOMLEFT, 100,30
            MerchantRepairAllButton:ClearAllPoints()
            MerchantRepairAllButton:SetPoint("BOTTOMRIGHT", MerchantFrame, "BOTTOMLEFT", 118+50-16-13, 30+3)
            -- sellingButton:SetPoint("RIGHT", MerchantRepairItemButton , "LEFT", -3 ,0 ) -- antiguamente
            sellingButton:SetPoint("BOTTOMRIGHT", MerchantFrame , "BOTTOMLEFT", 105-37-16 ,31 )
        elseif CanMerchantRepair() then
            MerchantRepairAllButton:ClearAllPoints()
            MerchantRepairAllButton:SetPoint("BOTTOMRIGHT", MerchantFrame, "BOTTOMLEFT", 118+50, 30+3)
            -- MerchantRepairItemButton:ClearAllPoints() -- no hace falta moverlo porque es right left de -8 a MerchantRepairItemButton
            -- MerchantRepairItemButton:SetPoint("BOTTOMRIGHT", MerchantFrame, "BOTTOMLEFT", 123, 30+3)
            -- sellingButton:SetPoint("BOTTOMRIGHT", MerchantFrame , "BOTTOMLEFT", 105-37 ,31 )
            sellingButton:SetPoint("BOTTOMRIGHT", MerchantFrame , "BOTTOMLEFT", 105-37 ,31 )
        else
            sellingButton:SetPoint("BOTTOMRIGHT", MerchantFrame , "BOTTOMLEFT", 105+16 ,31 )
        end
        sellingButton:Show()
        -- MerchantRepairText:Hide()
    end
end

local merchantOpened = false

-- esta funcion se llama todo el tiempo al lootear dinero de los bichos también aunque no esté el vendedor abierto, hay que salirse rápido
hooksecurefunc('MerchantFrame_UpdateRepairButtons', function() -- cuando dice que merchantshowsup, muchas veces no están los iconos, te lleva a error , y después aparece esto.
    if merchantOpened then
        --print ("AutoScrap jumping")
        repositionButtons()
    end
end)

-- :) 11.1.0
MerchantSellAllJunkButton:HookScript("OnShow",function (self)
        self:Hide() 
    end 
)

function ns.MerchantShowsUp ()
    merchantOpened = true
    if MerchantFrameTab1 then 
        MerchantFrameTab1:Show()
    end
    if MerchantFrameTab2 then 
        MerchantFrameTab2:Show()
    end
    if MerchantFrameTab3 then 
        MerchantFrameTab3:Show()
    end
    repositionButtons()
    --if CanMerchantRepair() and AutoScrap_CharSettings.autoRepair then --be more agressive, sometimes canmerchantrepair says no
    if AutoScrap_CharSettings.autoRepair then
        --RepairAllItems(0) --no es 0, está mal la wiki
        if GetRepairAllCost() > 0 then
            RepairAllItems(false) --false sin guild.
        end

        ----------quito esta parte redundantes, si alguien se queja que no reparar, reactivarla
        --[[ if MerchantRepairAllButton then --not necessary.
            MerchantRepairAllButton:Click()
        end
        C_Timer.After(300/1000,function ()
            if AutoScrap_CharSettings.autoRepair then --not necessary
                --RepairAllItems(0)
                RepairAllItems(false)
                if MerchantRepairAllButton then
                    MerchantRepairAllButton:Click()
                end
            end
        end) ]]
        ------------------fin de la parte quitada para reanudar si alguuien se queja que no repara
    end
    frameSellingInventory:Hide()
    if AutoScrap_CharSettings.autoSell then
        startAutoSelling()
    end
end

local Totalcount = 0
function ns.merchantClose()
    merchantOpened = false
    Totalcount = 0
    if MerchantFrameTab1 then 
        MerchantFrameTab1:Show()
    end
    if MerchantFrameTab2 then 
        MerchantFrameTab2:Show()
    end
    if MerchantFrameTab3 then 
        MerchantFrameTab3:Show()
    end
end

function pressedFunc(notFirstTime)
    local max = 12
    for b = 0, NUM_TOTAL_BAG_FRAMES do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            if max > 0 then
                local itemID = C_Container.GetContainerItemID(b,i)
                if itemID then
                    local price = select(11, GetItemInfo(itemID))
                    --local icon, itemCount, locked = GetContainerItemInfo(b, i)
                    local tablaItemInfo = C_Container.GetContainerItemInfo(b, i)
                    if tablaItemInfo and price and tablaItemInfo["iconFileID"] and tablaItemInfo["isLocked"]~=nil and not tablaItemInfo["isLocked"] and (ns.isJunkAS(itemID) or ns.isJunkBL(itemID)) and not AutoScrap_CharSettings.noVenderList[itemID] then
                        if price > 0 then
                            ClearCursor()
                            C_Container.UseContainerItem(b, i)
                            max = max -1
                        else
                            if notFirstTime then
                            ClearCursor()
                            C_Container.PickupContainerItem(b, i)
                            DeleteCursorItem()
                            max = max -1
                            end
                        end
                    end
                end
            end
        end
    end
end

frameSellingInventory = CreateFrame("Frame", nil, MerchantFrame)
frameSellingInventory:SetSize(160-40,30)
frameSellingInventory:SetPoint("TOPLEFT",MerchantFrame,"BOTTOMLEFT",5,0)

frameSellingInventory.tex = frameSellingInventory:CreateTexture()
frameSellingInventory.tex:SetColorTexture(2/255, 1/255, 39/255 , 0.9)
frameSellingInventory.tex:SetAllPoints(frameSellingInventory)
frameSellingInventory:Hide()

frameSellingInventory.texto = frameSellingInventory:CreateFontString (nil, "OVERLAY", "GameFontNormal")
frameSellingInventory.texto:SetText(L["Selling"])
--frameSellingInventory.texto:SetPoint("LEFT",frameSellingInventory,"LEFT",10,0)
frameSellingInventory.texto:SetPoint("CENTER",frameSellingInventory,"CENTER",0,0)

local function itemsLeftToSell()
    local count = 0
    for b = 0, NUM_TOTAL_BAG_FRAMES do
        for i = 1, C_Container.GetContainerNumSlots(b) do
            local itemID = C_Container.GetContainerItemID(b,i)
            if itemID then
                local price = select(11, GetItemInfo(itemID))
                if price and price ~= 0 and (ns.isJunkAS(itemID) or ns.isJunkBL(itemID)) and not AutoScrap_CharSettings.noVenderList[itemID] then
                    count = count + 1
                end
            end
        end
    end
    return count
end

local function finishSelling()
    frameSellingInventory:Hide()
    if MerchantFrameTab1 then 
        MerchantFrameTab1:Show()
    end
    if MerchantFrameTab2 then 
        MerchantFrameTab2:Show()
    end
    if MerchantFrameTab3 then 
        MerchantFrameTab3:Show()
    end
end

local function isErrorPopupWellKnown() --hacer click para automatizar el mensaje de error y no parar, o devolver false para parar
    if StaticPopup1.which == "CONFIRM_MERCHANT_TRADE_TIMER_REMOVAL" then
        StaticPopup1Button1:Click()
        return true
    end
    return false
end

local function recursiveFunction(firstTime)
    if firstTime or MerchantFrame:IsShown() then
        local left = itemsLeftToSell()
        if  left > 0 then
            frameSellingInventory.texto:SetText(L["Sold: "]..Totalcount-left.."/"..Totalcount)
            pressedFunc(false)
            if (StaticPopup1:IsShown()) then
                if not isErrorPopupWellKnown() then
                    finishSelling()
                else
                    C_Timer.After(100/1000,function () recursiveFunction(false) end)
                end
            else
                C_Timer.After(100/1000,function () recursiveFunction(false) end)
            end
        else
            finishSelling()
        end
    end
end


local function recursiveBlizzardJunkSell()
    sellBlizzardJunk()
    if C_MerchantFrame.GetNumJunkItems() > 0 then
        C_Timer.After(0.1, recursiveBlizzardJunkSell)
    end
end

startAutoSelling = function ()
    frameSellingInventory:Show()
    if MerchantFrameTab1 then 
        MerchantFrameTab1:Hide()
    end
    if MerchantFrameTab2 then 
        MerchantFrameTab2:Hide()
    end
    if MerchantFrameTab3 then 
        MerchantFrameTab3:Hide()
    end
    Totalcount = itemsLeftToSell()
    if Totalcount>0 then
        frameSellingInventory.texto:SetText(L["Sold: "].."0".."/"..Totalcount)
        recursiveFunction(true)
    else
        frameSellingInventory:Hide()
        if MerchantFrameTab1 then 
            MerchantFrameTab1:Show()
        end
        if MerchantFrameTab2 then 
            MerchantFrameTab2:Show()
        end
        if MerchantFrameTab3 then 
            MerchantFrameTab3:Show()
        end
    end
    if AutoScrap_CharSettings.blizzardDefaultJunk then
        recursiveBlizzardJunkSell()
    end
end

--setTooltip(frameSellingInventory,L["AutoScrap Selling Button"], L["Click on this button to sell 12 items from your inventory that AutoScrap or you has marked as Scrap."],L["Please note that items with no selling price will be destroyed, but you need to click this button to sell them, otherwise they cannot be destroyed without a hardware event."])