BINDING_HEADER_AAL_TWEAKS_BINDINGS = "AAL Tweaks / WoW 2.x-4.x";

local function in_array(value, ...)
  for i=1,select('#', ...) do
    if value == select(i, ...) then return true end
  end
  return false
end


local function CreateFMacro(name, code, eventScript, ...)
  local f = CreateFrame("Button", name, UIParent, "SecureActionButtonTemplate")
  f:RegisterForClicks("AnyUp")
  f:SetAttribute("type", "macro")
  if code ~= nil then f:SetAttribute("macrotext", code) end
  if eventScript ~= nil then
     f:SetScript("OnEvent", eventScript)
     for i=1,select('#', ...) do
		f:RegisterEvent(select(i, ...))
     end
  end
  return f
end


local function EventHandler(self, event, ...)
  --[[
    Здесь можно устанавливать SetBinding...(), но Wow (1.12,3.3.5a) сбрасывает
    их после входа в настройки клавиатуры + выхода без сохранения.
    Зато SetOverrideBinding...() не сбрасываются при выходе из настроек
  ]]
  SetConsoleKey("NUMLOCK")
  if ChatFrameEditBox ~= nil then
     ChatFrameEditBox:SetAltArrowKeyMode(false)
  else
     for i=1,7 do
       local curr = getglobal("ChatFrame"..i.."EditBox")
       if curr ~= nil then curr:SetAltArrowKeyMode(false) end
     end
  end
  SetOverrideBindingClick(self, false, "ALT-D", "aal_fDismount")
  SetOverrideBindingClick(self, false, "SHIFT-T", "aal_fPetStay")
  SetOverrideBindingClick(self, false, "ALT-T", "aal_fPetFollow")

  SetMapToCurrentZone();
  local cont = GetCurrentMapContinent()
  local tar = {}
  -- Instances
  if IsInInstance() then cont = -2; tar[1] = [[
/tar Panzor the Invincible
/tar Pyromancer Loregrain
/tar Verek
/tar Warder Stilgiss
/tar Lord Hel'nurath
/tar Tsu'zee
/tar Dark Iron Ambassador
/tar Bannok Grimaxe
/tar Burning Felguard
/tar Crystal Fang
/tar Ghok Bashguud
/tar Spirestone Battle Lord
/tar Spirestone Butcher
/tar Spirestone Lord Magus
/tar Cursed Centaur
/tar Meshlok the Harvester
/tar Ragglesnout
/tar Blind Hunter
/tar Earthcaller Halmgar
/tar Azshir the Sleepless
/tar Fallen Champion
/tar Ironspine
/tar Deathsworn Captain
/tar Bruegal Ironknuckle
/tar Hearthsinger Forresten
/tar Skul#
/tar Stonespine
/tar Veyzhak the Cannibal
/tar Zekkis
/tar Brainwashed Noble
/tar Marisa du'Paige
/tar Miner Johnson
/tar Digmaster Shovelphlange
/tar Goraluk Anvilcrack
/tar Jed Runewatcher
/tar Boahn
/tar Deviate Faerie Dragon
/tar Trigore the Lasher
/tar Dustwraith
/tar Sandarr Dunereaver
/tar Zerillis
]]
  -- Kalimdor
  elseif cont == 1 then tar = {
--[[Kalimdor 1]] [[
/tar Akkrilus
/tar Apothecary Falthis
/tar Branch Snapper
/tar Darkslayer Mordenthal
/tar Eck'alom
/tar Lady Vespia
/tar Mist Howler
/tar Mugglefin
/tar Oakpaw
/tar Prince Raze
/tar Rorgish Jowl
/tar Terrowulf Packlord
/tar Ursol'lok
/tar Antilos
/tar Gatekeeper Rageroar
/tar General Fangferror
/tar Lady Sesspira
/tar Magister Hawkhelm
/tar Master Feardred
/tar Monnos the Elder
/tar Scalebeard
/tar The Evalcharr
/tar Varo'then's Ghost
/tar Carnivous the Breaker
/tar Firecaller Radison
/tar Flagglemurk the Cruel
/tar Lady Moongazer
/tar Lady Vespira
/tar Licillin
/tar Lord Sinslayer
/tar Shadowclaw
/tar Strider Clutchmother
/tar Alshirr Banebreath
/tar Death Howl
/tar Dessecus
/tar Immolatus
/tar Mongress
/tar Olm the Wise
/tar Ragepaw
]],
--[[Kalimdor 2]] [[
/tar The Ongar
/tar Blackmoss the Fetid
/tar Duskstalker
/tar Fury Shelda
/tar Grimmaw
/tar Threggil
/tar Uruson
/tar Azurous
/tar General Colbatann
/tar Grizzle Snowpaw
/tar Kashoch the Reaver
/tar Lady Hederine
/tar Mezzir the Howler
/tar Rak'shiri
/tar Captain Flat Tusk
/tar Death Flayer
/tar Felweaver Scornn
/tar Geolord Mottle
/tar Warlord Kolkanis
/tar Watch Commander Zalaphil
/tar Brimgore
/tar Burgle Eye
/tar Darkmist Widow
/tar Dart#
/tar Drogoth the Roamer
/tar Hayoc
/tar Lord Angler
/tar Oozeworm
/tar Ripscale
/tar The Rot
/tar Enforcer Emilgund
/tar Ghost Howl
/tar Mazzranache
/tar Sister Hatelash
/tar Snagglespear
/tar The Rake
/tar Aean Swiftriver
/tar Ambassador Bloodrage
/tar Azzere the Skyblade
]],
--[[Kalimdor 3]] [[
/tar Brokespear
/tar Brontus
/tar Captain Gerogg Hammertoe
/tar Digger Flameforge
/tar Dishu
/tar Elder Mystic Razorsnout
/tar Engineer Whirleygig
/tar Foreman Grills
/tar Geopriest Gukk'rok
/tar Gesharahan
/tar Hagg Taurenbane
/tar Hannah Bladeleaf
/tar Heggin Stonewhisker
/tar Humar the Pridelord
/tar Malgin Barleybrew
/tar Marcus Bel
/tar Rathorian
/tar Rocklance
/tar Silithid Harvester
/tar Sister Rathtalon
/tar Sludge Beast
/tar Snort the Heckler
/tar Stonearm
/tar Swiftmane
/tar Swinegart Spearhide
/tar Takk the Leaper
/tar Thora Feathermoon
/tar Thunderstomp
/tar Achellios the Banished
/tar Gibblesnik
/tar Harb Foulmountain
/tar Heartrazor
/tar Ironeye the Invincible
/tar Silithid Ravager
/tar Vile Sting
/tar Accursed Slitherblade
/tar Crusty
/tar Giggler
/tar Hissperak
]],
--[[Kalimdor 4]] [[
/tar Kaskk
/tar Prince Kellen
/tar Antilus the Soarer
/tar Arash-ethis
/tar Bloodroar the Stalker
/tar Diamond Head
/tar Gnarl Leafbrother
/tar Lady Szallah
/tar Old Grizzlegut
/tar Qirot
/tar Snarler
/tar Gretheer
/tar Grubthor
/tar Huricanian
/tar Krellack
/tar Lapress
/tar Rex Ashil
/tar Setis
/tar Twilight Lord Everun
/tar Zora
/tar Brother Ravenoak
/tar Foreman Rigger
/tar Nal'taszar
/tar Pridewing Patriarch
/tar Sentinel Amarassan
/tar Sister Riven
/tar Sorrow Wing
/tar Taskmaster Whipfang
/tar Vengeful Ancient
/tar Cyclok the Mad
/tar Greater Firebird
/tar Haarka the Ravenous
/tar Jin'Zallah the Sandbringer
/tar Kregg Keelhaul
/tar Murderous Blisterpaw
/tar Omgorn the Lost
/tar Soriid the Devourer
/tar Warleader Krazzilak
/tar Clutchmother Zavas
/tar Gruff
/tar King Mosh
/tar Ravasaur Matriarch
/tar Uhk'loc

/tar Mushgog
/tar Skarr the Unbreakable
/tar The Razza
]]
}
  -- Eastern Kingdoms
  elseif cont == 2 then tar = {
--[[EK 1]] [[
/tar Araga
/tar Cranky Benj
/tar Gravis Slipknot
/tar Jimmy the Bleeder
/tar Lo'Grosh
/tar Narillasanz
/tar Skhowl
/tar Stone Fury
/tar Darbel Montrose
/tar Foulbelly
/tar Geomancer Flintdagger
/tar Kovork
/tar Molok the Crusher
/tar Nimar the Slayer
/tar Prince Nazjak
/tar Ruul Onestone
/tar Singer
/tar Zalas Witherbark
/tar Deathspeaker Selendre
/tar Duggan Wildhammer
/tar Gish the Unmoving
/tar Hed'mush the Rotting
/tar High General Abbendis
/tar Baron Bloodbane
/tar Lord Darkscythe
/tar Nerubian Overseer
/tar Ranger Lord Hawkspear
/tar Warlord Thresh'jin
/tar Zul'Brin Warpbranch
/tar Big Samras
/tar Creepthess
/tar Lady Zephris
/tar Ro'Bark
/tar Scargil
/tar Tamra Stormpike
/tar Foreman Jerris
/tar Foreman Marcrid
/tar Foulmane
/tar Lord Maldazzar
/tar Putridius
/tar Scarlet Executioner
/tar Scarlet High Clerist
/tar Scarlet Interrogator
/tar Scarlet Judge
/tar Scarlet Smith
]],
--[[EK 2]] [[
/tar The Husk
/tar Grimungous
/tar Ironback
/tar Jalinde Summerdrake
/tar Mith'rethis the Enchanter
/tar Old Cliff Jumper
/tar Razortalon
/tar Retherokk the Berserker
/tar The Reak
/tar Witherheart the Stalker
/tar Zul'arek Hatefowler
/tar Bayne
/tar Deeb
/tar Farmer Solliden
/tar Fellicent's Shade
/tar Lost Soul
/tar Muad
/tar Ressan the Needler
/tar Sri'skulk
/tar Tormented Spirit
/tar Dalaran Spellscribe
/tar Gorefang
/tar Krethis Shadowspinner
/tar Old Vicejaw
/tar Ravenclaw Regent
/tar Rot Hide Bruiser
/tar Snarlmane
/tar Scarshield Quartermaster
/tar The Behemoth
/tar Bjarn
/tar Edan the Howler
/tar Gibblewilt
/tar Great Father Arctikus
/tar Hammerspine
/tar Timber
/tar 7:XT
/tar Anathemus
/tar Barnabus
/tar Broken Tooth
/tar Rumbler
/tar Shadowforge Commander
/tar Siege Golem
/tar War Golem
/tar Zaricotl
]],
--[[EK 3]] [[
/tar Akubar the Seer
/tar Clack the Reaver
/tar Deatheye
/tar Dreadscorn
/tar Dreadwhisper
/tar Grunter
/tar Magronos the Unyielding
/tar Mojo the Twisted
/tar Ravage
/tar Spiteflayer
/tar Deathmaw
/tar Gorgon'och
/tar Gruklash
/tar Hahk'Zor
/tar Hematos
/tar Malfunctioning Reaver
/tar Terrorspark
/tar Thauris Balgarr
/tar Volchan
/tar Morick Darkbrew
/tar Boss Galgosh
/tar Emogg the Crusher
/tar Grizlak
/tar Gosh-Haldir
/tar Large Loch Crocolisk
/tar Lord Condar
/tar Magosh
/tar Shanda the Spinner
/tar Faulty War Golem
/tar Highlord Mastrogonde
/tar Rekk'tilac
/tar Scald
/tar Shleipnarr
/tar Slave Master Blackheart
/tar Smoldar
/tar Dragonmaw Battlemaster
/tar Garneg Charskull
/tar Gnawbone
/tar Leech Widow
/tar Ma'ruk Wyrmscale
/tar Mirelow
/tar Razormaw Matriarch
/tar Sludginn
/tar Commander Felstrom
/tar Fenros
]],
--[[EK 4]] [[
/tar Lord Malathrom
/tar Lupos
/tar Marina DeSirrus
/tar Naraxis
/tar Nefaru
/tar The Unknown Soldier
/tar Gug Fatcandle
/tar Fedfennel
/tar Gruff Swiftbite
/tar Morgaine the Sly
/tar Mother Fang
/tar Narg the Taskmaster
/tar Thuros Lightfingers
/tar Boulderheart
/tar Chatter
/tar Kazon
/tar Ribchaser
/tar Rohh the Silent
/tar Seeker Aqualon
/tar Snarlflare
/tar Squiddic
/tar Sewer Beast
/tar Gluggle
/tar High Priestess Hai'watna
/tar Kurmokk
/tar Lord Sakrasis
/tar Mosh'Ogg Butcher
/tar Rippa
/tar Roloch
/tar Scale Belly
/tar Verifonix
/tar Fingat
/tar Gilmorian
/tar Lord Captain Wyrmak
/tar Lost One Chieftain
/tar Lost One Cook
/tar Molt Thorn
/tar Brack
/tar Foe Reaper 4000
/tar Leprithus
/tar Master Digger
/tar Sergeant Brashclaw
/tar Slark
/tar Vultros

/tar Jade#
/tar Eldinarcus
/tar Tregla
/tar Dr. Whitherlimb
]]
}
  -- Outland: мобы из зон Draenei и Blood Elves заносятся и в Outland, и в
  -- Calimdor/Eastern Kingdoms, т.к. PLAYER_ENTERING_WORLD не вызывается при
  -- переходе между любыми зонами дополнения Burning Crusade
  elseif cont == 3 then tar[1] = [[
/tar Hemathion
/tar Morcrush
/tar Speaker Mar'grom
/tar Fulgorge
/tar Mekthorg the Wild
/tar Vorakem Doomspeaker
/tar Bro'Gaz the Clanless
/tar Goretooth
/tar Voidhunter Yar
/tar Chief Engineer Lorthander
/tar Ever-Core the Punisher
/tar Nuramoc
/tar Ambassador Jerrikar
/tar Collidus the Warp-Watcher
/tar Kraator
/tar Crippler
/tar Doomsayer Jurim
/tar Okrek
/tar Bog Lurker
/tar Coilfang Emissary
/tar Marticar

/tar Fenissa the Assassin
/tar Eldinarcus
/tar Tregla
/tar Dr. Whitherlimb
]]
  -- Northrend
  elseif cont == 4 then tar[1] = [[
/tar Fumblub Gearwind
/tar Icehorn
/tar Old Crystalbark
/tar Vern
/tar Crazed Indu'le Survivor
/tar Scarlet Highlord Daion
/tar Tukemuth
/tar Arcturis
/tar Grocklar
/tar Seething Hate
/tar Syreian the Bonecarver
/tar King Ping
/tar Perobas the Bloodthirster
/tar Vigdis the War Maiden
/tar High Thane Jorfus
/tar Hildana Deathstealer
/tar Putridus the Ancient
/tar Aotona
/tar King Krush
/tar Loque'nahak
/tar Dirkee
/tar Skoll
/tar Time-Lost Proto Drake
/tar Vyragosa
/tar Gondria
/tar Griegen
/tar Terror Spinner
/tar Zul'drak Sentinel
]]
  -- Cataclysm zones
  else tar[1] = [[
/tar Ghostcrawler
/tar Mobus
/tar Shok'sharak
/tar Aeonaxx
/tar Golgarok
/tar Jadefang
/tar Terborus
/tar Xariona
/tar Lady La-La
/tar Blazewing
/tar Garr
/tar Terrorpene
/tar Thartuk the Exile
/tar Burgy Blackheart
/tar Captain Florence
/tar Captain Foulwind
/tar Poseidus
/tar Julak-Doom
/tar Karoma
/tar Overlord Sunderfury
/tar Sambas
/tar Tarvus the Vile
/tar Akma'hat
/tar Armagedillo
/tar Cyrus the Black
/tar Dormus the Camel-Hoarder
/tar Madexx
]]
  end
  for i = 1,4 do
    local mt
    if tar[i] ~= nil then
       if i == 1 then mt = "/cleartarget\n"..tar[i] else mt = tar[i] end
       if tar[i+1] ~= nil then
          mt = mt.."\n/click aal_fScanNPC"..(i+1)
       else
          mt = mt.."\n/run AAL_TRotate()"
       end
    end
    _G["aal_fScanNPC"..i]:SetAttribute("macrotext", mt)
    --print("@"..cont, "Rare NPC pool ["..i.."] =", string.len(mt))
  end
  SetOverrideBindingClick(self, false, "ALT-G", "aal_fScanNPC1")
end


function AAL_TRotate()
  if not UnitExists("target") then return end
  local name = GetUnitName("target")
  local mt, iB, iE
  for i=4,1,-1 do
    mt = _G["aal_fScanNPC"..i]:GetAttribute("macrotext")
    if mt ~= nil then

    iB, iE = string.find(mt, "/tar "..name.."\n",1,true)
    if iB then
       -- удаляем с найденной позиции в списке целей
       mt = string.sub(mt, 1, iB-1)..string.sub(mt, iE+1, -1)
       local mt_pre
       for k=i,1, -1 do
         if not (i == k) then mt = mt_pre end
         if k == 1 then
            iB = string.find(mt, "/tar ",1,true)
            if iB then
               -- добавляем перед первой из целей в списке
               mt = string.sub(mt, 1, iB-1).."/tar "..name.."\n"..string.sub(mt, iB, -1);
            end
         else
            -- перемещаем последнюю из целей предшествующего блока в начало этого
            mt_pre = _G["aal_fScanNPC"..(k-1)]:GetAttribute("macrotext")
            for iB = string.len(mt_pre)-6,1, -1 do
              if string.sub(mt_pre, iB, iB+5) == "\n/tar " then
                 iB = iB+1
                 iE = string.find(mt_pre, "\n", iB+5, true)
                 if iE then
                    local moved = string.sub(mt_pre, iB, iE)
                    mt_pre = string.sub(mt_pre, 1, iB-1)..string.sub(mt_pre, iE+1, -1)
                    mt = moved..mt
                    --print("Moved \""..moved.."\"; Remains \""..string.len(mt_pre).."\"")
                 end
                 break
              end
            end
         end
         --print("rare NPC pool ["..k.."] =", string.len(mt))
         _G["aal_fScanNPC"..k]:SetAttribute("macrotext", mt)
       end
       --DEFAULT_CHAT_FRAME:AddMessage("Your sixth sense reveals nearby presense of "..name, 0.59,0.68,0.92)
       break
    end

    end
  end
  if iB == nil then print("AAL_Tweak warning! something is wrong in AAL_TRotate()") end
end



-- ONLOAD CODE

if IsSpellPassive == nil then IsSpellPassive = IsPassiveSpell end -- WoW 2.0.1
if GetSpellName == nil then GetSpellName = GetSpellBookItemName end -- WoW 4.0.1
if print==nil then
function print(...)
   local str = ""
   for _, v in ipairs{...} do
     if v == nil then break end
     str = str.." "..tostring(v)
   end
   DEFAULT_CHAT_FRAME:AddMessage(str)
end
end

local version, build = GetBuildInfo()
AAL_wow_version = version
AAL_wow_build = tonumber(build)

CreateFMacro("aal_fDismount",
  "/run if UnitInVehicle ~= nil and UnitInVehicle('player') then VehicleExit() end\n/dismount [mounted]\n/cast [form] Travel Form",
  EventHandler, "PLAYER_ENTERING_WORLD", "ZONE_CHANGED_NEW_AREA")

CreateFMacro("aal_fPetStay", "/petstay")
CreateFMacro("aal_fPetFollow", "/petfollow")

CreateFMacro("aal_fScanNPC1")
CreateFMacro("aal_fScanNPC2")
CreateFMacro("aal_fScanNPC3")
CreateFMacro("aal_fScanNPC4")

print("AAL tweaks: WoW", AAL_wow_version.."."..AAL_wow_build)

