------------------------------
--      Are you local?      --
------------------------------

local boss = BB["Archimonde"]
local L = AceLibrary("AceLocale-2.2"):new("BigWigs"..boss)
local db = nil

local UnitName = UnitName
local pName = UnitName("player")
local IsItemInRange = IsItemInRange
local GetRaidRosterInfo = GetRaidRosterInfo
local GetNumRaidMembers = GetNumRaidMembers
local fmt = string.format
local wipe = wipe
-- Original 2.4.3 does not provide the global wipe helper.
if type(wipe) ~= "function" then
	wipe = function(tbl)
		if type(tbl) ~= "table" then
			return tbl
		end
		for k in pairs(tbl) do
			tbl[k] = nil
		end
		return tbl
	end
end
local bandages = {
	[21991] = true, -- Heavy Netherweave Bandage
	[21990] = true, -- Netherweave Bandage
	[14530] = true, -- Heavy Runecloth Bandage
	[14529] = true, -- Runecloth Bandage
	[8545] = true, -- Heavy Mageweave Bandage
	[8544] = true, -- Mageweave Bandage
	[6451] = true, -- Heavy Silk Bandage
	[6450] = true, -- Silk Bandage
	[3531] = true, -- Heavy Wool Bandage
	[3530] = true, -- Wool Bandage
	[2581] = true, -- Heavy Linen Bandage
	[1251] = true, -- Linen Bandage
}

local gripLabels = {}

----------------------------
--      Localization      --
----------------------------

L:RegisterTranslations("enUS", function() return {
	cmd = "Archimonde",

	engage_trigger = "Your resistance is insignificant.",
	engage_message = boss.." engaged!",

	grip = "Grip of the Legion",
	grip_desc = "Warn who has Grip of the Legion.",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "Raid Icon",
	icon_desc = "Place a Raid Icon on the player with Grip of the Legion.",

	fear = "Fear",
	fear_desc = "Fear Timers.",
	fear_bar = "~Fear Cooldown",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "Air Burst",
	burst_desc = "Warn who Air Burst is being cast on.",
	burst_other = "Air Burst on -%s-",
	burst_you = "Air Burst on YOU!",

	burstsay = "Air Burst Say",
	burstsay_desc = "Print in say when you are targetted for Air Burst, can help nearby members with speech bubbles on.",
	burstsay_message = "Air Burst on me!",
} end )

L:RegisterTranslations("esES", function() return {
	engage_trigger = "Vuestra resistencia es insignificante.",
	engage_message = boss.." engaged!",

	grip = "Apretón de la Legión (Grip of the Legion)",
	grip_desc = "Avisar quién tiene Apretón de la Legión.",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "Icono de banda",
	icon_desc = "Poner un icono de banda sobre jugadores afectados por Apretón de la Legión. (Requiere derechos de banda)",

	fear = "Miedo (Fear)",
	fear_desc = "Contadores para Miedo.",
	fear_bar = "~Miedo",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "Ráfaga de aire (Air Burst)",
	burst_desc = "Avisar quién tiene Ráfaga de aire.",
	burst_other = "Ráfaga de aire en -%s-",
	burst_you = "¡Ráfaga de aire en TI!",

	burstsay = "Decir Ráfaga de aire",
	burstsay_desc = "Alertar en el canal Decir cuando eres el objetivo de Ráfaga de aire, puede ayudar a compañeros cercanos con bocadillos de chat activos.",
	burstsay_message = "¡Ráfaga de aire en mí!",
} end )

L:RegisterTranslations("frFR", function() return {
	engage_trigger = "Votre résistance est futile.",
	engage_message = boss.." engaged!",

	grip = "Poigne de la Légion",
	grip_desc = "Prévient quand un joueur subit les effets de la Poigne de la Légion.",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "Icône",
	icon_desc = "Place une icône de raid sur le dernier joueur affecté par la Poigne de la Légion.",

	fear = "Peur",
	fear_desc = "Délais concernant les Peurs.",
	fear_bar = "~Recharge Peur",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "Jaillissement d'air",
	burst_desc = "Prévient sur qui le Jaillissement d'air est incanté.",
	burst_other = "Jaillissement d'air sur -%s-",
	burst_you = "Jaillissement d'air sur VOUS !",

	burstsay = "Dire - Jaillissement d'air",
	burstsay_desc = "Fait dire à votre personnage que vous êtes ciblé par le Jaillissement d'air quand c'est le cas, afin d'aider les membres proches ayant les bulles de dialogue activées.",
	burstsay_message = "Jaillissement d'air sur moi !",
} end )

L:RegisterTranslations("koKR", function() return {
	engage_trigger = "아무리 저항해도 소용없다!",
	engage_message = boss.." engaged!",

	grip = "군단의 손아귀",
	grip_desc = "군단의 손아귀에 걸린 사람을 알립니다.",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "전술 표시",
	icon_desc = "군단의 손아귀에 걸린 플레이어에게 전술 표시를 지정합니다. (승급자 이상 권한 요구)",

	fear = "공포",
	fear_desc = "공포 타이머입니다.",
	fear_bar = "~공포 대기시간",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "대기 파열",
	burst_desc = "대기 파열 시전 대상을 알립니다.",
	burst_other = "-%s- 대기 파열",
	burst_you = "당신은 대기 파열!",

	burstsay = "대기 파열 알림",
	burstsay_desc = "자신이 대기 파열의 대상이 되었을 때 일반 대화로 알립니다.",
	burstsay_message = "저! 대기 파열! 피하세요!!",
} end )

L:RegisterTranslations("deDE", function() return {
	engage_trigger = "Euer Widerstand ist sinnlos!",
	engage_message = boss.." engaged!",

	grip = "Würgegriff der Legion",
	grip_desc = "Warnt wer den Würgegriff der Legion hat.",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "Schlachtzug Symbol",
	icon_desc = "Plaziert ein Schlachtzug Symbol auf Spielern mit Würgegriff der Legion Debuff.",

	fear = "Furcht",
	fear_desc = "Furcht Timer.",
	fear_bar = "~Furcht Cooldown",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "Windbö",
	burst_desc = "Warnt auf wen Windbö gezaubert wird.",
	burst_other = "Windbö auf -%s-",
	burst_you = "Windbö auf DIR!",

	burstsay = "Windbö Sagen",
	burstsay_desc = "Schreibe in /sagen wenn du das Ziel von Windbö bist, dies kann angrenzenden Membern mit aktivierten Sprechblasen helfen.",
	burstsay_message = "Windbö auf mir!",
} end )

L:RegisterTranslations("zhCN", function() return {
	engage_trigger = "你们的抵抗是毫无意义的。",
	engage_message = boss.." engaged!",

	grip = "军团之握",
	grip_desc = "当玩家受到军团之握时发出警报。",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "团队标记",
	icon_desc = "给中了军团之握的队友打上团队标记。（需要权限）",

	fear = "恐惧",
	fear_desc = "恐惧计时。",
	fear_bar = "<恐惧 冷却>",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "空气爆裂",
	burst_desc = "当开始施放空气爆裂时发出警报。",
	burst_other = "空气爆裂：>%s<！",
	burst_you = ">你< 空气爆裂！",

	burstsay = "空气爆裂（说）",
	burstsay_desc = "当你为空气爆裂目标时警报周围，以帮助附近的队友远离。",
	burstsay_message = "我中了空气爆裂！离开我...",
} end )

L:RegisterTranslations("zhTW", function() return {
	engage_trigger = "你反抗是沒有用的。",
	engage_message = boss.." engaged!",

	grip = "軍團之握",
	grip_desc = "受到軍團之握時發送警告",
	grip_you = "Decurse YOU!",
	grip_other = "Decurse %s",
	grip_other_group = "Decurse %s (Group %d)",

	icon = "團隊標記",
	icon_desc = "在受到軍團之握的隊友頭上標記 (需要權限)",

	fear = "恐懼術",
	fear_desc = "恐懼術計時器",
	fear_bar = "<恐懼術冷卻>",
	fear_five = "Fear in 5 Seconds!",
	fear_countdown = "Fear in %d!",
	fearcount = "Fear Countdown",
	fearcount_desc = "Announce 'Fear in 3, 2, 1' during the final seconds before each Fear.",
	fearten = "Fear 10 Audio",
	fearten_desc = "Play a local-only sound 10 seconds before each Fear.",

	burst = "空氣炸裂",
	burst_desc = "當空氣炸裂施放時時發送警告",
	burst_other = "空氣炸裂: [%s]",
	burst_you = "空氣炸裂在你身上!",

	burstsay = "空氣炸裂 (說)",
	burstsay_desc = "當你為空氣爆裂目標時警報周圍，以幫助附近的隊友遠離。",
	burstsay_message = "空氣炸裂在我身上!",
} end )

----------------------------------
--      Module Declaration      --
----------------------------------

local mod = BigWigs:NewModule(boss)
mod.zonename = BZ["Hyjal Summit"]
mod.enabletrigger = boss
mod.guid = 17968
mod.toggleoptions = {"grip", "icon", "fear", "fearcount", "fearten", "burst", "burstsay", "proximity", "bosskill"}
mod.revision = tonumber(("$Revision: 78512 $"):sub(12, -3))
mod.defaultDB = {
	fearcount = false,
	fearten = false,
}
mod.proximityCheck = function( unit ) 
	for k, v in pairs( bandages ) do
		if IsItemInRange( k, unit) == 1 then
			return true
		end
	end
	return false
end
mod.proximitySilent = true

------------------------------
--      Initialization      --
------------------------------

function mod:OnEnable()
	self:AddCombatListener("SPELL_AURA_APPLIED", "Grip", 31972)
	self:AddCombatListener("SPELL_DISPEL", "GripRemoved")
	self:AddCombatListener("SPELL_CAST_START", "Burst", 32014)
	self:AddCombatListener("SPELL_CAST_START", "Fear", 31970)
	self:AddCombatListener("UNIT_DIED", "BossDeath")

	self:RegisterEvent("CHAT_MSG_MONSTER_YELL")
	self:RegisterEvent("PLAYER_REGEN_ENABLED", "CheckForWipe")

	db = self.db.profile
	wipe(gripLabels)
end

------------------------------
--      Event Handlers      --
------------------------------

local function getGroupNumber(player)
	if not player then return end
	for i = 1, GetNumRaidMembers() do
		local name, _, subGroup = GetRaidRosterInfo(i)
		if name == player then
			return subGroup
		end
	end
end

function mod:GetGripLabel(player)
	local group = getGroupNumber(player)
	if group then
		return fmt(L["grip_other_group"], player, group)
	end
	return fmt(L["grip_other"], player)
end

function mod:GetGripMessageLabel(player)
	local group = getGroupNumber(player)
	local colored = self:ColorName(player)
	if group then
		return fmt(L["grip_other_group"], colored, group)
	end
	return fmt(L["grip_other"], colored)
end

function mod:StartFearTimer(duration, icon)
	if db.fear then
		self:Bar(L["fear_bar"], duration, icon)
	end
	if db.fearten and duration > 10 then
		self:ScheduleEvent("BWArchimondeFearTenSound", "BigWigs_Sound", duration - 10, "BigWigs: Archimonde Fear 10")
	end
	if not db.fear then return end
	if duration > 5 and not db.fearcount then
		self:DelayedMessage(duration - 5, L["fear_five"], "Important")
	end
	if db.fearcount then
		if duration > 5 then
			self:DelayedMessage(duration - 5, fmt(L["fear_countdown"], 5), "Attention")
		end
		if duration > 4 then
			self:DelayedMessage(duration - 4, fmt(L["fear_countdown"], 4), "Attention")
		end
		if duration > 3 then
			self:DelayedMessage(duration - 3, fmt(L["fear_countdown"], 3), "Attention")
		end
		if duration > 2 then
			self:DelayedMessage(duration - 2, fmt(L["fear_countdown"], 2), "Attention")
		end
		if duration > 1 then
			self:DelayedMessage(duration - 1, fmt(L["fear_countdown"], 1), "Attention")
		end
	end
end

function mod:Grip(player, spellID)
	if db.grip then
		local label = self:GetGripLabel(player)
		local msgLabel = self:GetGripMessageLabel(player)
		if player == pName then
			self:LocalMessage(L["grip_you"], "Attention", spellID, "Long")
			self:WideMessage(msgLabel)
		else
			self:IfMessage(msgLabel, "Attention", spellID)
		end
		self:Bar(label, 10, spellID)
		gripLabels[player] = label
		self:Icon(player, "icon")
	end
end

function mod:GripRemoved(player, _, _, spellID)
	if spellID and spellID == 31972 then
		if db.grip then
			local label = gripLabels[player]
			if label then
				self:TriggerEvent("BigWigs_StopBar", self, label)
				gripLabels[player] = nil
			end
		end
	end
end

function mod:Burst()
	if db.burst then
		self:ScheduleEvent("BWBurstToTScan", self.TargetCheck, 0.2, self)
	end
end

function mod:Fear(_, spellID)
	self:StartFearTimer(41, spellID)
end

function mod:CHAT_MSG_MONSTER_YELL(msg)
	if msg == L["engage_trigger"] then
		self:Message(L["engage_message"], "Attention")
		if db.enrage then
			self:Enrage(540)
		end
		self:StartFearTimer(40, "Spell_Shadow_DeathScream")
		self:TriggerEvent("BigWigs_ShowProximity", self)
	end
end

function mod:TargetCheck()
	local target
	if UnitName("target") == boss then
		target = UnitName("targettarget")
	elseif UnitName("focus") == boss then
		target = UnitName("focustarget")
	else
		local num = GetNumRaidMembers()
		for i = 1, num do
			if UnitName(fmt("%s%d%s", "raid", i, "target")) == boss then
				target = UnitName(fmt("%s%d%s", "raid", i, "targettarget"))
				break
			end
		end
	end
	if target then
		if target == pName then
			self:LocalMessage(L["burst_you"], "Personal", 32014, "Long")
			self:WideMessage(fmt(L["burst_other"], self:ColorName(target)))
			if db.burstsay then
				SendChatMessage(L["burstsay_message"], "SAY")
			end
		else
			self:IfMessage(fmt(L["burst_other"], self:ColorName(target)), "Attention", 32014)
		end
	end
end

