local _ -- THEY SAID THEY FIXED IT BUT I DON'T BELIEVE THEM :<

local IChooseYou = LibStub("AceAddon-3.0"):NewAddon("IChooseYou", "AceEvent-3.0", "AceTimer-3.0")

local addon, ns = ...
local cfg = ns.cfg
local playing = { open = false, vict = false, }
local battle, id, m
local musicVolume, musicOn

hooksecurefunc("Sound_ToggleMusic", function () 
  if GetCVar("Sound_EnableMusic") == 0 then
    IChooseYou:Stop()
  elseif C_PetBattles.IsInBattle() then
    IChooseYou:PET_BATTLE_OPENING_START()
  end
end)

function IChooseYou:Stop()
  self:CancelAllTimers()
  StopMusic()
  
  if playing.open then
    StopSound(playing.open)
    playing.open = false
  end

  if playing.vict then
    StopSound(playing.vict)
    playing.vict = false
  end
end

function IChooseYou:PET_BATTLE_OPENING_START()
  self:Stop()
  
  battle = C_PetBattles.IsWildBattle() and "wild" or "train"
  id = cfg.favorite or math.random(#cfg.music)
  m = cfg.music[id][battle]
 
  PlayMusic("Interface\\AddOns\\IChooseYou\\Music\\Silence.ogg") -- fucking zone music
  _, playing.open = PlaySoundFile(m.open, cfg.alwaysOn and "Master" or "Music")
  
  self:ScheduleTimer(function ()
    if cfg.alwaysOn then 
      musicVolume = GetCVar("Sound_MusicVolume")
      musicOn = GetCVar("Sound_EnableMusic")
      SetCVar("Sound_MusicVolume", GetCVar("Sound_MasterVolume"))
      SetCVar("Sound_EnableMusic", 1) 
    end
    PlayMusic(m.loop)
  end, m.oDur)
end

function IChooseYou:PET_BATTLE_FINAL_ROUND(event, winner)
  self:Stop()
  
  if winner == 1 then
    _, playing.vict = PlaySoundFile(m.vict, cfg.alwaysOn and "Master" or "Music")
    PlayMusic("Interface\\AddOns\\IChooseYou\\Music\\Silence.ogg")
    self:ScheduleTimer(function ()
      StopMusic()
      if cfg.alwaysOn then 
        SetCVar("Sound_EnableMusic", musicOn) 
        SetCVar("Sound_MusicVolume", musicVolume)
      end
    end, m.vDur)
  else
    StopMusic()
    if cfg.alwaysOn then 
      SetCVar("Sound_EnableMusic", musicOn) 
      SetCVar("Sound_MusicVolume", musicVolume)
    end
  end
end

function IChooseYou:OnEnable()
  self:RegisterEvent("PET_BATTLE_OPENING_START")
  self:RegisterEvent("PET_BATTLE_FINAL_ROUND")
end

function IChooseYou:OnDisable()
  self:UnregisterAllEvents()
end