-- tools tab
setDefaultTab("Tools")


if type(storage.parcelItemsToMove) ~= "table" then
  storage.parcelItemsToMove = {11587, 11658, 942, 22707}
end

local parcelId = 3504
local targetBackpackId = 16909

local function contains(t, val)
  for i = 1, #t do
    if t[i] == val then return true end
  end
  return false
end

macro(500, "Mover Itens da Parcel", function()
  local containers = g_game.getContainers()
  local targetIndex = nil

  -- Identificar a backpack de destino (ID 16909)
  for index, container in pairs(containers) do
    if container:getContainerItem():getId() == targetBackpackId then
      targetIndex = index
      break
    end
  end
  if not targetIndex then return end

  -- Procurar por parcels e mover todos os itens válidos
  for _, container in pairs(containers) do
    if container:getContainerItem():getId() == parcelId then
      for _, item in ipairs(container:getItems()) do
        if contains(storage.parcelItemsToMove, item:getId()) then
          g_game.move(item, {x=65535, y=targetIndex, z=0}, item:getCount())
          -- Não usar 'return' aqui, para continuar movendo os demais itens
        end
      end
    end
  end
end)


UI.TextEdit(storage.autoreset or "level", function(widget, text)
  storage.autoreset = tonumber(text) or 0 
end)

-- Macro
local autoreset = macro(10000, "Auto Reset", function()
  local targetLevel = tonumber(storage.autoreset) or 750000
  if player:getExperience() >= targetLevel then
    say("!reset")
  end
end)

-- Restaura estado salvo no storage (liga ou desliga o macro)
autoreset.setOn(storage.autoresetEnabled or false)

-- Botão com salvamento do estado
addIcon("autoreset", {item=37136, text="Auto RR"}, function(icon, isOn)
  autoreset.setOn(isOn)
  storage.autoresetEnabled = isOn
end)

UI.Separator()



local function checkPos(x, y)
 xyz = g_game.getLocalPlayer():getPosition()
 xyz.x = xyz.x + x
 xyz.y = xyz.y + y
 tile = g_map.getTile(xyz)
 if tile then
  return g_game.use(tile:getTopUseThing())
 else
  return false
 end
end

macro(1, 'Bug Map', function() 
 if modules.corelib.g_keyboard.isKeyPressed('w') then
  checkPos(0, -5)
 elseif modules.corelib.g_keyboard.isKeyPressed('e') then
  checkPos(3, -3)
 elseif modules.corelib.g_keyboard.isKeyPressed('d') then
  checkPos(5, 0)
 elseif modules.corelib.g_keyboard.isKeyPressed('c') then
  checkPos(3, 3)
 elseif modules.corelib.g_keyboard.isKeyPressed('s') then
  checkPos(0, 5)
 elseif modules.corelib.g_keyboard.isKeyPressed('z') then
  checkPos(-3, 3)
 elseif modules.corelib.g_keyboard.isKeyPressed('a') then
  checkPos(-5, 0)
 elseif modules.corelib.g_keyboard.isKeyPressed('q') then
  checkPos(-3, -3)
 end
end)

-----------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------


-- Macro para usar Pot 500% exp
macro(10000, "200% Food", function()
  if not isInPz() then
      use(6542)
  end
end)

-- Macro para usar Pot 200% exp
macro(10000, "300% Food", function()
  if not isInPz() then
      use(6543)
  end
end)

-- Macro para usar Pot 50% exp
macro(5000, "400% Food", function()
  if not isInPz() then
      use(6544)
  end
end)

macro(5000, "500% Food", function()
  if not isInPz() then
      use(6545)
  end
end)

macro(5000, "600% Food", function()
  if not isInPz() then
      use(3215)
  end
end)

macro(5000, "700% Food", function()
  if not isInPz() then
      use(6541)
  end
end)

macro(5000, "800% Food", function()
  if not isInPz() then
      use(11682)
  end
end)

macro(5000, "1000% Food", function()
  if not isInPz() then
      use(9655)
  end
end)

-----------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
--------------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------

-- Macro para usar Stamina
macro(250, "Usar Stamina", function()
  local Stamina = player:getStamina()
  if Stamina < 2401 and not isInPz() then
      use(9087)
  end
end)



macro(500, "Auto Haste", nil, function()
  if not hasHaste() and storage.autoHasteText:len() > 0 then
    if saySpell(storage.autoHasteText) then
      delay(5000)
    end
  end
end)
addTextEdit("autoHasteText", storage.autoHasteText or "utani mega hur", function(widget, text) 
  storage.autoHasteText = text
end)

macro(1000, "Abrir proxima Bag", function()
  local containers = getContainers()
  for i, container in pairs(containers) do
    if container:getItemsCount() == container:getCapacity() then
      for _, item in ipairs(container:getItems()) do
        if item:isContainer() then
          g_game.open(item, container)
        end
      end
    end
  end
end)


local mineableIds = {21799}
local pickaxes = {22882, 22887, 22771, 16967, 3456} -- Adicione aqui as picaretas da melhor para a pior
local useDistance = 1
local moveDist = 1 -- Distância máxima para caminhar até o mineral

-- Função para encontrar a melhor picareta disponível
local function getBestPickaxe()
    for _, pickId in ipairs(pickaxes) do
        for _, container in pairs(g_game.getContainers()) do
            for _, item in ipairs(container:getItems()) do
                if item:getId() == pickId then
                    return item
                end
            end
        end
    end
    return nil
end

macro(10, "Minerar", function()
    local pickaxe = getBestPickaxe()
    if not pickaxe then return end

    for _, tile in ipairs(g_map.getTiles(posz())) do
        for _, item in ipairs(tile:getItems()) do
            if item and table.contains(mineableIds, item:getId()) then
                local distance = getDistanceBetween(pos(), tile:getPosition())

                if distance <= useDistance then
                    g_game.useWith(pickaxe, item)
                    return
                end

                if distance <= moveDist and distance > useDistance then
                    autoWalk(tile:getPosition(), moveDist, {ignoreNonPathable=true, precision=1})
                    delay(100)
                end
            end
        end
    end
end)



-- Auto magic shield
macro(100, "Utamo Vita", function()
    if(not hasManaShield()) then
        say('utamo vita')
    end
end)
-----------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
local distance = 5
local amountOfMonsters = 2
macro(500, "Spellcaster",  function()
    local specAmount = 0
    if not g_game.isAttacking() then
        return
    end
    for i,mob in ipairs(getSpectators()) do
        if (getDistanceBetween(player:getPosition(), mob:getPosition())  <= distance and mob:isMonster())  then
            specAmount = specAmount + 1
        end
    end
    if (specAmount >= amountOfMonsters) then
        say(storage.AOEText)
    else
        say(storage.SingleTargetText)
    end
end)
UI.Label("Single Target Spell")
addTextEdit("SingleTragetText", storage.SingleTargetText or "exori vis", function(widget, singleText) 
    storage.SingleTargetText = singleText
end)
UI.Label("Multi Target Spell")
addTextEdit("AOEText", storage.AOEText or "exevo gran mas vis", function(widget, multiText) 
    storage.AOEText = multiText
end)
-----------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
storage.hpPercent = storage.hpPercent or 95
storage.HealText = storage.HealText or "exura"

macro(400, "Spell Healing", function()
    if not storage.HealText then return end
    if hppercent() <= storage.hpPercent then
        say(storage.HealText)
    end
end)

addTextEdit("HealText", storage.HealText, function(widget, text)
    storage.HealText = text
end)

UI.Label("Health %:")
local hpSlider = setupUI([[
HorizontalScrollBar
  id: hpSlider
  width: 150
  height: 12
  minimum: 0
  maximum: 100
  step: 1
  margin-top: 5
]])

local hpTextEdit = UI.TextEdit(tostring(storage.hpPercent), function(widget, text)
    local value = tonumber(text)
    if value and value >= 0 and value <= 100 then
        storage.hpPercent = value
        if hpSlider then
            hpSlider:setValue(value)
        end
    else
        widget:setText(tostring(storage.hpPercent))
    end
end)
hpTextEdit:setWidth(50)

if hpSlider then
    hpSlider:setValue(storage.hpPercent)
    hpSlider.onValueChange = function(widget, value)
        storage.hpPercent = value
        if hpTextEdit then
            hpTextEdit:setText(tostring(value))
        end
        widget:setTooltip("Heal at " .. value .. "% HP")
    end
end

-----------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------

storage.mpPercent = storage.mpPercent or 85
storage.ManaHealText = storage.ManaHealText or "exura ico"

macro(400, "Spell Mana Healing", function()
    if not storage.ManaHealText then return end
    if manapercent() <= storage.mpPercent then
        say(storage.ManaHealText)
    end
end)

addTextEdit("ManaHealText", storage.ManaHealText, function(widget, text)
    storage.ManaHealText = text
end)

UI.Label("Mana %:")
local mpSlider = setupUI([[
HorizontalScrollBar
  id: mpSlider
  width: 150
  height: 12
  minimum: 0
  maximum: 100
  step: 1
  margin-top: 5
]])

local mpTextEdit = UI.TextEdit(tostring(storage.mpPercent), function(widget, text)
    local value = tonumber(text)
    if value and value >= 0 and value <= 100 then
        storage.mpPercent = value
        if mpSlider then
            mpSlider:setValue(value)
        end
    else
        widget:setText(tostring(storage.mpPercent))
    end
end)
mpTextEdit:setWidth(50)

if mpSlider then
    mpSlider:setValue(storage.mpPercent)
    mpSlider.onValueChange = function(widget, value)
        storage.mpPercent = value
        if mpTextEdit then
            mpTextEdit:setText(tostring(value))
        end
        widget:setTooltip("Heal at " .. value .. "% Mana")
    end
end


-----------------------------------------------------------------------------
UI.Separator()
-----------------------------------------------------------------------------
storage.followLeader = storage.followLeader or "Quentin"

FollowMacro = macro(1231321321, "Follow", function() end)

addTextEdit("playerToFollow", storage.followLeader, function(widget, text)
  storage.followLeader = text
end)


onCreaturePositionChange(function(creature, newPos, oldPos)
  if FollowMacro:isOff() then return end

  if newPos and oldPos and creature:getName() == player:getName() and getCreatureByName(storage.followLeader) == nil and newPos.z > oldPos.z then
    say('exani tera')
    for i = -1, 1 do
      for j = -1, 1 do
        local useTile = g_map.getTile({ x = posx() + i, y = posy() + j, z = posz() })
        g_game.use(useTile:getTopUseThing())
      end
    end
  end
  if creature:getName() == storage.followLeader then
    if not newPos then
      if oldPos then
        lastPos = oldPos

        schedule(200, function()
          autoWalk(oldPos)
        end)
      end

      schedule(1000, function()
        for i = -1, 1 do
          for j = -1, 1 do
            local useTile = g_map.getTile({ x = posx() + i, y = posy() + j, z = posz() })
            if useTile then
              local top useTile:getTopUseThing()
              if top then
                g_game.use(top)
              end
            end
          end
        end
      end)
    end

    if not newPos or not oldPos then return end
    if oldPos.z == newPos.z then
      schedule(300, function()
        local useTile = g_map.getTile({ x = oldPos.x, y = oldPos.y, z = oldPos.z })
        topThing = useTile:getTopThing()

        if not useTile:isWalkable() then
          use(topThing)
        end
      end)


      autoWalk({ x = oldPos.x, y = oldPos.y, z = oldPos.z })
    else
      lastPos = oldPos
      autoWalk(oldPos)
      for i = 1, 6 do
        schedule(i * 200, function()
          autoWalk(oldPos)

          if getDistanceBetween(pos(), oldPos) == 0 and (posz() > newPos.z and getCreatureByName(storage.followLeader) == nil) then
            say('exani tera')
          end
        end)
      end
      local useTile = g_map.getTile({ x = newPos.x, y = newPos.y - 1, z = oldPos.z })
      g_game.use(useTile:getTopUseThing())
    end
  end
end)
-----------------------------------------------------------------------------


macro(60000, "Send message on trade", function()
  local trade = getChannelId("advertising")
  if not trade then
    trade = getChannelId("trade")
  end
  if trade and storage.autoTradeMessage:len() > 0 then    
    sayChannel(trade, storage.autoTradeMessage)
  end
end)
UI.TextEdit(storage.autoTradeMessage or "I'm using OTClientV8!", function(widget, text)    
  storage.autoTradeMessage = text
end)

UI.Separator()
