---@diagnostic disable: undefined-global, redefined-local
local Twins = DBM:NewBossMod("Twins", DBM_TWINS_NAME, DBM_TWINS_DESCRIPTION, DBM_SUNWELL, DBM_SW_TAB, 4)

Twins.Version		= "1.0"
Twins.Author		= "Tandanu"

--Define pyrogenics popup frame
local pyroPopup = CreateFrame("Frame","DBM_Twins_Pyro_Popup",UIParent)
pyroPopup:SetHeight(65)
pyroPopup:SetWidth(65)
pyroPopup:EnableMouse(true)
pyroPopup:SetMovable(true)
pyroPopup:SetPoint("TOPLEFT", 400, -300)
pyroPopup.icon = pyroPopup:CreateTexture(nil, "ARTWORK")
pyroPopup.icon:SetAllPoints(true)
local _,_,dsIcon = GetSpellInfo(45230)
pyroPopup.icon:SetTexture(dsIcon)
pyroPopup:Hide()

--global variables
local healthFrame, maxhp, hp, prct_hp, current_vulnerability;
local last_alythess_hp_update = GetTime()
local last_sacrolash_hp_update = GetTime()
local phase = 1
local dead_p1_boss = "None"
local soaks_count = 1
local conflag_count = 1
local shadow_nova_count = 1

Twins:RegisterCombat("COMBAT", 2, DBM_TWINS_MOB_WL, DBM_TWINS_NAME, {DBM_TWINS_MOB_WL, DBM_TWINS_MOB_SOCR})

--Alythess Options
Twins:AddOption("PyrogenicsPopup", true, "Show Pyrogenics Popup")
Twins:AddOption("WhisperConflag", true, DBM_TWINS_OPTION_CONFLAG2)
Twins:AddOption("SpecWarnConflag", true, DBM_TWINS_OPTION_CONFLAG3)
Twins:AddOption("IconConflag", true, DBM_TWINS_OPTION_CONFLAG4)
Twins:AddOption("SoundWarnConflag", true, DBM_TWINS_OPTION_CONFLAG5)

--Sacrolash Options
Twins:AddOption("WhisperNova", true, DBM_TWINS_OPTION_NOVA2)
Twins:AddOption("SpecWarnNova", true, DBM_TWINS_OPTION_NOVA3)
Twins:AddOption("IconNova", false, DBM_TWINS_OPTION_NOVA4)

--General Options
Twins:AddOption("VulnFilter", false, "Only show timers related to your vulnerability")
Twins:AddOption("DarkTouch", true, DBM_TWINS_OPTION_TOUCH1)
--Twins:AddOption("FlameTouch", false, DBM_TWINS_OPTION_TOUCH2)
Twins:AddOption("ShowHPFrame", true, "Show health frame", function()
	Twins.Options.ShowHPFrame = not Twins.Options.ShowHPFrame
	if Twins.Options.ShowHPFrame and Twins.InCombat then
		Twins:CreateHealthFrame()
	end
end)

--Timers
Twins:AddBarOption("Enrage")
Twins:AddBarOption("Next Conflagration")
Twins:AddBarOption("Next Shadow Nova")
Twins:AddBarOption("Next Circle Soaks")
Twins:AddBarOption("Next Inferno")
Twins:AddBarOption("Next Dark Spin")
Twins:AddBarOption("Next Vulnerability Swap")
Twins:AddBarOption("10 second kill window")

Twins:RegisterEvents(
	"SPELL_CAST_START",
	"SPELL_CAST_SUCCESS",
	"SPELL_AURA_APPLIED",
	"SPELL_AURA_REMOVED",
	"SPELL_DAMAGE",
	"CHAT_MSG_RAID_BOSS_EMOTE",
	"SPELL_AURA_APPLIED_DOSE"
)

function Twins:OnCombatStart(delay)
	phase = 1
	dead_p1_boss = "None"
	current_vulnerability = "Unknown"
	soaks_count = 1
	conflag_count = 1
	shadow_nova_count = 1

	self:StartStatusBarTimer(360 - delay, "Enrage", "Interface\\Icons\\Spell_Shadow_UnholyFrenzy")
	if self.Options.ShowHPFrame then
		self:CreateHealthFrame()
	end
end

function Twins:OnCombatEnd()
	self:HideHealthFrame()
	pyroPopup:Hide()
end

function Twins:OnEvent(event, args)
	if event == "SPELL_CAST_SUCCESS" then
		if args.spellId == 22959 then --Fire Vulnerability casted
			self:ScheduleSelf(1, "VulnerabilitySwap")
		elseif args.spellId == 19695 and phase == 2 then
			self:StartStatusBarTimer(75, "Next Inferno", "Interface\\Icons\\Spell_Fire_Incinerate")
		end
	elseif event == "SPELL_CAST_START" then
		if args.spellId == 45342 and phase == 2 then --conflag
			conflag_count = conflag_count + 1
			if conflag_count % 2 == 0 then
				self:StartStatusBarTimer(30, "Next Conflagration", "Interface\\Icons\\Spell_Fire_Fireball02")
			else
				self:StartStatusBarTimer(45, "Next Conflagration", "Interface\\Icons\\Spell_Fire_Fireball02")
			end
		elseif args.spellId == 45329 and phase == 2 then --shadow nova
			shadow_nova_count = shadow_nova_count + 1
			if shadow_nova_count % 2 == 0 then
				self:StartStatusBarTimer(30, "Next Shadow Nova", 45329)
			else
				self:StartStatusBarTimer(45, "Next Shadow Nova", 45329)
			end
		end
	elseif event == "VulnerabilitySwap" then
		for i=1,12 do
			local debuffName = UnitDebuff("player", i)
			if debuffName ~= nil then
				if debuffName == "Shadow Shell" then current_vulnerability = "Shadow" end
				if debuffName == "Growing Flames" then current_vulnerability = "Fire" end
			end
		end

		self:StartStatusBarTimer(14, "Next Circle Soaks", "Interface\\Icons\\Spell_Arcane_Blast")
		self:ScheduleSelf(14, "Circle Soaks");

		if not self.Options.VulnFilter or current_vulnerability == "Fire" then
			self:StartStatusBarTimer(24, "Next Conflagration", "Interface\\Icons\\Spell_Fire_Fireball02")
			self:ScheduleSelf(24, "Conflagration");

			self:StartStatusBarTimer(29, "Next Inferno", "Interface\\Icons\\Spell_Fire_Incinerate")
			self:StartStatusBarTimer(74, "Next Vulnerability Swap", "Interface\\Icons\\Inv_Enchant_ShardGlimmeringLarge")
		end

		if not self.Options.VulnFilter or current_vulnerability == "Shadow" then
			self:StartStatusBarTimer(24, "Next Shadow Nova", 45329)
			self:ScheduleSelf(24, "Shadow Nova");

			self:StartStatusBarTimer(29, "Next Dark Spin", "Interface\\Icons\\Inv_Sword_2h_Blood_C_01")
		end
	elseif event == "Circle Soaks" then
		--this event is only used in phase 1
		self:StartStatusBarTimer(30, "Next Circle Soaks", "Interface\\Icons\\Spell_Arcane_Blast")
	elseif event == "Conflagration" then
		--this event is only used in phase 1
		self:StartStatusBarTimer(30, "Next Conflagration", "Interface\\Icons\\Spell_Fire_Fireball02")
	elseif event == "Shadow Nova" then
		--this event is only used in phase 1
		self:StartStatusBarTimer(30, "Next Shadow Nova", 45329)
	elseif event == "SPELL_AURA_APPLIED" then
		if args.spellId == 45230 and args.destName == DBM_TWINS_MOB_WL and self.Options.PyrogenicsPopup then
			pyroPopup:Show()
		elseif args.spellId == 30502 and phase == 2 then
			self:StartStatusBarTimer(75, "Next Dark Spin", "Interface\\Icons\\Inv_Sword_2h_Blood_C_01")
		end
	elseif event == "SPELL_AURA_REMOVED" then
		if args.spellId == 45230 and args.destName == DBM_TWINS_MOB_WL and self.Options.PyrogenicsPopup then
			pyroPopup:Hide()
		end
	elseif event == "SPELL_AURA_APPLIED_DOSE" then
		if self.Options.DarkTouch and args.spellId == 45347 and args.destName == UnitName("player") and args.amount >= 8 then
			self:AddSpecialWarning(DBM_TWINS_SPECWARN_SHADOW:format(args.amount))
		--elseif self.Options.FlameTouch and args.spellId == 45348 and args.destName == UnitName("player") and args.amount >= 5 then
		--	self:AddSpecialWarning(DBM_TWINS_SPECWARN_FIRE:format(args.amount))
		end
	elseif event == "CHAT_MSG_RAID_BOSS_EMOTE" then
		local _, _,target = (args or ""):find(DBM_TWINS_EMOTE_CONFLAG)
		if target then
			self:SendSync("Conflagration"..target)
		end
		target = nil

		local _, _,target = (args or ""):find(DBM_TWINS_EMOTE_NOVA)
		if target then
			self:SendSync("ShadowNova"..target)
		end

		if arg1 == "Magic Affinity has been disrupted!" then
			phase = 2
			if healthFrame ~= nil then
				healthFrame:Hide()
			end

			self:EndStatusBarTimer("Next Conflagration")
			self:EndStatusBarTimer("Next Shadow Nova")
			self:EndStatusBarTimer("Next Circle Soaks")
			self:EndStatusBarTimer("Next Inferno")
			self:EndStatusBarTimer("Next Dark Spin")
			self:EndStatusBarTimer("Next Vulnerability Swap")
			self:EndStatusBarTimer("10 second kill window")

			self:StartStatusBarTimer(15, "Next Circle Soaks", "Interface\\Icons\\Spell_Arcane_Blast")     --after this, soak timers are handled by looking for a boss emote
			self:StartStatusBarTimer(30, "Next Inferno", "Interface\\Icons\\Spell_Fire_Incinerate")       --after this, inferno timer is handled by a SPELL_CAST_SUCCESS event
			self:StartStatusBarTimer(30, "Next Dark Spin", "Interface\\Icons\\Inv_Sword_2h_Blood_C_01")   --after this, dark spin timer is handled by a SPELL_AURA_APPLIED event
			self:StartStatusBarTimer(25, "Next Conflagration", "Interface\\Icons\\Spell_Fire_Fireball02") --after this, conflag timer is handled by a SPELL_CAST_START event
			self:StartStatusBarTimer(39, "Next Shadow Nova", 45329)                                       --after this, shadow nova timer is handled by a SPELL_CAST_START event
		elseif arg1 == "The twins begin to unleash powerful spells!" then
			soaks_count = soaks_count + 1
			if soaks_count % 2 == 0 then
				self:StartStatusBarTimer(30, "Next Circle Soaks", "Interface\\Icons\\Spell_Arcane_Blast")
			else
				self:StartStatusBarTimer(45, "Next Circle Soaks", "Interface\\Icons\\Spell_Arcane_Blast")
			end
		end
	end
end

function Twins:OnSync(msg)
	if msg:sub(0, 13) == "Conflagration" then
		msg = msg:sub(14)
		if self.Options.WhisperConflag then
			self:SendHiddenWhisper(DBM_TWINS_WHISPER_CONFLAG, msg)
		end
		if msg == UnitName("player") then
			if self.Options.SoundWarnConflag then
				PlaySoundFile("Sound\\Spells\\PVPFlagTaken.wav")
				PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.wav")
			end
			if self.Options.SpecWarnConflag then
				self:AddSpecialWarning(DBM_TWINS_WHISPER_CONFLAG)
			end
		end
		if self.Options.IconConflag then
			self:SetIcon(msg, 8)
		end
	elseif msg:sub(0, 10) == "ShadowNova" then
		msg = msg:sub(11)
		if self.Options.WhisperNova then
			self:SendHiddenWhisper(DBM_TWINS_WHISPER_NOVA, msg)
		end
		if msg == UnitName("player") and self.Options.SpecWarnNova then
			self:AddSpecialWarning(DBM_TWINS_WHISPER_NOVA)
		end
		if self.Options.IconNova then
			self:SetIcon(msg,7)
		end
	end
end

function Twins:CreateHealthFrame()
	if healthFrame then
		healthFrame:Show()
		healthFrame.bar1:SetValue(100)
		getglobal(healthFrame.bar1:GetObject():GetName().."RightText"):SetText("100%")
		healthFrame.bar1:GetObject():SetStatusBarColor(0, 1, 0)
		healthFrame.bar2:SetValue(100)
		getglobal(healthFrame.bar2:GetObject():GetName().."RightText"):SetText("100%")
		healthFrame.bar2:GetObject():SetStatusBarColor(0, 1, 0)
	else
		healthFrame = DBMGui:CreateInfoFrame("Twins HP")

		local scale = GetCVar("uiScale")
		local borderWidth = 2 / scale
		local borderColor = {1, 1, 1}
		local backdrop = {
			bgFile = "Interface/Tooltips/UI-Tooltip-Background",
			edgeFile = "Interface\\Buttons\\WHITE8x8",
			tileEdge = false,
			edgeSize = borderWidth,
			insets = {left = borderWidth, right = borderWidth, top = borderWidth, bottom = borderWidth},
		}
		healthFrame["Frame"]:SetBackdrop(backdrop)
		healthFrame["Frame"]:SetBackdropBorderColor(borderColor[1], borderColor[2], borderColor[3], 1)
		healthFrame.bar1 = healthFrame:CreateStatusBar(0, 100, 100, nil, "Alythess", "100%")
		healthFrame.bar1:GetObject():SetStatusBarTexture("Interface\\AddOns\\DBM_API\\Textures\\Smoothv2")
		healthFrame.bar2 = healthFrame:CreateStatusBar(0, 100, 100, nil, "Sacrolash", "100%")
		healthFrame.bar2:GetObject():SetStatusBarTexture("Interface\\AddOns\\DBM_API\\Textures\\Smoothv2")
	end
end

function Twins:HideHealthFrame()
	if healthFrame then
		healthFrame:Hide()
	end
end

Twins.UpdateInterval = 0.2;
function Twins:OnUpdate()
	if (GetTime() - last_alythess_hp_update < 0.25) and (GetTime() - last_sacrolash_hp_update < 0.25) then return end;
	for i = 1, GetNumRaidMembers() do
		if UnitName("raid"..i.."target") then
			if UnitName("raid"..i.."target") == "Grand Warlock Alythess" then
				maxhp = UnitHealthMax("raid"..i.."target")
				hp = UnitHealth("raid"..i.."target")
				prct_hp = math.floor(hp / maxhp * 100)
				if healthFrame ~= nil then
					healthFrame.bar1:SetValue(prct_hp)
					getglobal(healthFrame.bar1:GetObject():GetName().."RightText"):SetText(tostring(prct_hp).."%")
				end
				last_alythess_hp_update = GetTime()
				if hp == 1 and dead_p1_boss == "None" then
					dead_p1_boss = "Grand Warlock Alythess"
					self:StartStatusBarTimer(9.5, "10 second kill window", "Interface\\Icons\\Ability_Rogue_Feigndeath")
				end
				if hp > 1 and dead_p1_boss == "Grand Warlock Alythess" then
					dead_p1_boss = "None"
				end
			elseif UnitName("raid"..i.."target") == "Lady Sacrolash" then
				maxhp = UnitHealthMax("raid"..i.."target")
				hp = UnitHealth("raid"..i.."target")
				prct_hp = math.floor(hp / maxhp * 100)
				if healthFrame ~= nil then
					healthFrame.bar2:SetValue(prct_hp)
					getglobal(healthFrame.bar2:GetObject():GetName().."RightText"):SetText(tostring(prct_hp).."%")
				end
				last_sacrolash_hp_update = GetTime()
				if hp == 1 and dead_p1_boss == "None" then
					dead_p1_boss = "Lady Sacrolash"
					self:StartStatusBarTimer(9.5, "10 second kill window", "Interface\\Icons\\Ability_Rogue_Feigndeath")
				end
				if hp > 1 and dead_p1_boss == "Lady Sacrolash" then
					dead_p1_boss = "None"
				end
			end
		end
	end
end
