Merfin = Merfin or {}

--[[
-- Localizing functions
local GetTime, GetInstanceInfo, GetSpellInfo = GetTime, GetInstanceInfo, GetSpellInfo
local select, wipe, bband, pairs = select, wipe, bit.band, pairs
local stformat = string.format
local UnitTokenFromGUID, UnitDetailedThreatSituation = UnitTokenFromGUID, UnitDetailedThreatSituation
local UnitHealth, UnitHealthMax, UnitExists = UnitHealth, UnitHealthMax, UnitExists
local GetNameplates = C_NamePlate.GetNamePlates
local SendWA_Event = WeakAuras.ScanEvents

local CORE = {}
Merfin.CORE = CORE
Merfin.RAID = {

    -- Link to Core
    CORE = CORE,

    -- Defaults
    settings = {
        visibility = {
            COOLDOWN = true,
        },
        
        cooldowns = {
            hold = true,
            alpha = true,
            customNames = true,
        }, 
    }

}

local localized = {
    ['enUS'] = {
        berserk =        'Berserk',
        phase   =        'Phase',
        phase_2 =        'Phase 1',
        phase_2 =        'Phase 2',
        phase_3 =        'Phase 3',
        phase_4 =        'Phase 4',
        boss_activated = 'Boss Activated',
        stop_attack =    'Stop Attacking',
        gtfo =           'GTFO',
        run_away =       'RUN AWAY',
        switch =         'SWITCH',
        air_phase =      'Air Phase',
        ground_phase =   'Ground Phase',
        interrupt =      'Interrupt',
        fight_start =    'Fight start',
    },
}
local L = localized[GetLocale()] or localized['enUS']

CORE.L = L

CORE.mechanics = {
    berserk = { 26662 },
}

local settings = Merfin.RAID.settings
local mainEvent = 'WA_MERFIN_RAID'

local GetInstanceInfo = function()
    local _,_, id = GetInstanceInfo()
    if id == 3 then
        return '10_NORMAL'
    elseif id == 4 then
        return '25_NORMAL'
    elseif id == 5 then
        return '10_HEROIC'
    elseif id == 6 then
        return '25_HEROIC'
    end
end

local BuildValuesString = function(names)
    local str = ''
    for i, name in pairs(names) do
        local formattedName = WA_ClassColorName(name) or name
        if str == '' then
            str = formattedName
        else
            str = stformat('%s, %s', str, formattedName)
        end
    end
    return str
end

CORE.PlayerGUID = UnitGUID('player')

CORE.IsNPC = function(destFlags)
    return bband(destFlags, COMBATLOG_OBJECT_TYPE_NPC) ~= 0
end

CORE.IsPlayer = function(args)
    if args.destGUID and (args.destGUID == CORE.PlayerGUID) then
        return true
    end
end

CORE.IsTanking = function(sourceUnitId, destUnitId, destGUID)
    if not destUnitId and destGUID and UnitTokenFromGUID then
        destUnitId = UnitTokenFromGUID(destGUID)
    end
    if destUnitId then
        local isTanking = UnitDetailedThreatSituation(sourceUnitId, destUnitId)
        return isTanking
    end
end

CORE.IsDestTypePlayer = function(flags)
    if flags and COMBATLOG_OBJECT_TYPE_PLAYER then
        return bband(flags, COMBATLOG_OBJECT_TYPE_PLAYER) ~= 0
    end
end

CORE.GetGuidCreatureId = function(GUID)
    local guidType,_, playerdbID,_,_, cid,_ = strsplit("-", GUID or "")
    if guidType and (guidType == "Creature" or guidType == "Vehicle" or guidType == "Pet") then
        return tonumber(cid)
    elseif type and (guidType == "Player" or guidType == "Item") then
        return tonumber(playerdbID)
    end
    return 0
end

CORE.CetUnitCreatureId = function(unitId)
    if not UnitExists(unitId) then
        return 0
    end
    local unitGUID = UnitGUID(unitId)
    return CORE.GetGuidCreatureId(unitGUID)
end

local UnitIDPool = { "target", "focus", "mouseover", 'boss1', 'boss2', 'boss3', 'boss4', 'boss5' }
CORE.GetTarget = function(byGUID, byNpcId, context)
    local func = byGUID and UnitGUID or CORE.CetUnitCreatureId
    for _, unitID in ipairs(UnitIDPool) do
        if UnitExists(unitID) and func(unitID) == context then
            local targetUnitID = stformat("%starget", unitID)
            return targetUnitID
        end
    end
    local nameplates = GetNameplates()
    for _, plateData in pairs(nameplates) do
        local namePlateContext = byGUID and plateData.namePlateUnitGUID or plateData.namePlateNpcId
        if namePlateContext == context then
            local nameplateId = plateData.UnitFrame.displayedUnit
            local targetUnitID = stformat("%starget", nameplateId)
            return targetUnitID
        end
    end
    for unitID in WA_IterateGroupMembers() do
        local targetUnitID = stformat("%starget", unitID)
        if UnitExists(targetUnitID) and func(targetUnitID) == context then
            return stformat("%starget", targetUnitID)
        end
    end
end

CORE.GetNpcIdTarget = function(cid)
    return CORE.GetTarget(false, true, cid)
end
CORE.GetGuidTarget = function(guid)
    return CORE.GetTarget(true, false, guid)
end

CORE.GetRaidUnitByName = function(unitName)
    for i = 1, 40 do
        local unitId = 'raid' .. i
        if not UnitExists(unitId) then return end
        local uName = UnitName(unitId)
        if unitName == uName then
            return unitId
        end
    end
end

CORE.TargettedCast = function(sourceGUID, e)
    local targetUnit = CORE.GetGuidTarget(sourceGUID)
    local unitName = targetUnit and UnitName(targetUnit)
    if unitName then
        local raidId = CORE.GetRaidUnitByName(unitName)
        SendWA_Event(e, raidId, unitName)
    end
end

CORE.GetSettings = function(type, option)
    if not settings then return end
    return settings[type][option]
end

CORE.GetUnitHealthPercent = function(unitId)
    if not UnitExists(unitId) then return end
    local percent = 100 * UnitHealth(unitId) / UnitHealthMax(unitId)
    return percent
end

CORE.GetSpellCache = function(ENTRY, spellId)
    if not spellId then return end
    if not ENTRY.cache[spellId] then
        ENTRY.cache[spellId] = {}
        local name,_, icon = GetSpellInfo(spellId)
        ENTRY.cache[spellId].spellName = name
        ENTRY.cache[spellId].icon = icon
    end
    return ENTRY.cache[spellId].spellName, ENTRY.cache[spellId].icon
end

CORE.IsSpellId = function(spellId, ...)
    for i = 1, select("#", ...) do
        if spellId == select(i, ...) then
            return true
        end
    end
end

CORE.IsDifficulty = function(...)
    local difficulty = CORE.difficulty or GetInstanceInfo()
    for i = 1, select("#", ...) do
        if CORE.difficulty == select(i, ...) then
            return true
        end
    end
end

CORE.ResetFields = function(ENTRY)
    local tables = { 'counter', 'schedulers', 'antispams', 'cache', 'CASTS', 'ctx' }
    for _, t in pairs(tables) do
        if ENTRY[t] then
            wipe(ENTRY[t])
        else
            ENTRY[t] = {}
        end
    end
end

CORE.CancelScheduler = function(ENTRY, mechanic)
    local timer = ENTRY.schedulers[mechanic]
    if timer then
        WeakAuras.timer:CancelTimer(timer)
        ENTRY.schedulers[mechanic] = nil
    end
end

CORE.WipeSchedulers = function(ENTRY)
    if ENTRY.schedulers then
        for mechanic, timer in pairs(ENTRY.schedulers) do
            CORE.CancelScheduler(ENTRY, mechanic)
        end
    end
end

CORE.Schedule = function(ENTRY, mechanic, after, func, ...)
    if ENTRY.schedulers[mechanic] then WeakAuras.timer:CancelTimer(ENTRY.schedulers[mechanic]) end
    ENTRY.schedulers[mechanic] = WeakAuras.timer:ScheduleTimer(func, after, ...)
end

CORE.WipeCounter = function(type, mechanic)
    ENTRY.counter[type] = ENTRY.counter[type] or {}
    ENTRY.counter[type][mechanic] = 0
    return ENTRY.counter[type][mechanic]
end

CORE.AntiSpam = function(ENTRY, mechanic, timer)
    local t = GetTime()
    if not ENTRY.antispams[mechanic] or t - ENTRY.antispams[mechanic] > timer then
        ENTRY.antispams[mechanic] = t
        return true
    end
end

CORE.SetStage = function(ENTRY, n)
    ENTRY.stage = n
    SendWA_Event('PHASE_' .. n)
end

CORE.GetStage = function(ENTRY)
    return ENTRY.stage
end

CORE.IsStage = function(ENTRY, n)
    if not ENTRY.stage then return true end
    return ENTRY.stage == n
end

local IncrMechanic = function(ENTRY, type, mechanic)
    ENTRY.counter[type] = ENTRY.counter[type] or {}
    local count = ENTRY.counter[type][mechanic]
    ENTRY.counter[type][mechanic] = (count or 0) + 1
    return ENTRY.counter[type][mechanic]
end

local GetAutoHide = function()
    if not WeakAuras.CurrentEncounter then
        return true
    else
        return not CORE.GetSettings('cooldowns', 'hold')
    end
end

local GetMechanicInfo = function(ENTRY, mechanic)
    local spellName, icon
    if ENTRY.mechanics[mechanic] then
        local spellId = ENTRY.mechanics[mechanic][1]
        local cSpellName, cIcon = CORE.GetSpellCache(ENTRY, spellId)
        spellName = ENTRY.L[mechanic] or cSpellName
        icon = ENTRY.mechanics[mechanic][2] or cIcon
    elseif CORE.mechanics[mechanic] then
        local spellId = CORE.mechanics[mechanic][1]
        local cSpellName, cIcon = CORE.GetSpellCache(ENTRY, spellId)
        spellName = CORE.L[mechanic] or cSpellName
        icon = CORE.mechanics[mechanic][2] or cIcon
    else
        spellName = ENTRY.L[mechanic] or CORE.L[mechanic] or 'Unknown'
    end
    return spellName, icon
end


--> Handlers & Prototype

local WA_HandlerEvent = 'WA_MERFIN_RAID_HANDLER'
local SendEvent = function(...)
    SendWA_Event(WA_HandlerEvent, ...)
end

local SetState = function(duration, autoHide, name, icon, counter, destName, stacks)
    return {
        show = true,
        changed = true,
        progressType = 'timed',
        duration = duration,
        expirationTime = duration + GetTime(),
        autoHide = autoHide,
        name = name,
        icon = icon,
        counter = counter,
        destName = destName,
        stacks = stacks,
        CORE = CORE,
    }
end

local Handlers = {
    
    CANCEL = function(a, caller, mechanic, cancelType)
        if mechanic == caller.mechanic and (cancelType == 'ALL' or caller.type == cancelType) then
            local changed = false
            for _, state in pairs(a) do
                state.show = false
                state.changed = true
                changed = true
            end
            return changed
        end
    end,
    
    WARNING = function(a, caller, mechanic, name, icon, counter, destName, stacks)
        if mechanic == caller.mechanic and caller.type == 'WARNING' then
            local duration = 3
            local stateName = destName or ''
            a[stateName] = SetState(duration, true, name, icon, counter, destName, stacks)
            return true
        end
    end,
    
    SPECIAL_WARNING = function(a, caller, mechanic, ...)
        if mechanic == caller.mechanic and caller.type == 'SPECIAL_WARNING' then
            local duration = 3
            local stateName = ''
            a[stateName] = SetState(duration, true, ...)
            return true
        end
    end,
    
    PRE_WARNING = function(a, caller, mechanic, duration, ...)
        if mechanic == caller.mechanic and caller.type == 'PRE_WARNING' then
            local stateName = ''
            a[stateName] = SetState(duration, true, ...)
            return true
        end
    end,
    
    WARNING_MULTIPLY = function(a, caller, mechanic, name, icon, targets)
        if mechanic == caller.mechanic and caller.type == 'WARNING_MULTIPLY' then
            local duration = 3
            local stateName = ''
            a[stateName] = SetState(duration, true, name, icon)
            a[stateName].names = BuildValuesString(targets)
            return true
        end
    end,
    
    COOLDOWN = function(a, caller, mechanic, duration, name, icon, counter, sourceName, forceHide)
        if mechanic == caller.mechanic and caller.type == 'COOLDOWN' then
            local autoHide = forceHide or GetAutoHide()
            local stateName = sourceName or ''
            a[stateName] = SetState(duration, autoHide, name, icon, counter, sourceName)
            a[stateName].alphaOn = CORE.GetSettings('cooldowns', 'alpha')
            return true
        end
    end,
    
    TIMER = function(a, caller, mechanic, duration, ...)
        if mechanic == caller.mechanic and caller.type == 'TIMER' then
            local stateName = ''
            a[stateName] = SetState(duration, true, ...)
            return true
        end
    end,
    
    PHASE = function(a, caller, mechanic, ...)
        if mechanic == caller.mechanic and caller.type == 'PHASE' then
            local duration = 3
            local stateName = ''
            a[stateName] = SetState(duration, true, ...)
            return true
        end
    end,
    
    GTFO = function(a, caller, mechanic, ...)
        if mechanic == caller.mechanic and caller.type == 'GTFO' then
            local duration = 3
            local stateName = ''
            a[stateName] = SetState(duration, true, ...)
            a[stateName].GTFO = CORE.L['gtfo']
            return true
        end
    end,
    
}

local Prototype = {
    
    CANCEL = function(ENTRY, mechanic, cancelType)
        if cancelType == 'ALL' or cancelType == 'PRE_WARNING' then
            if ENTRY.schedulers[mechanic] then 
                WeakAuras.timer:CancelTimer(ENTRY.schedulers[mechanic]) 
            end
        end
        SendEvent(Handlers.CANCEL, mechanic, cancelType)
    end,
    
    WARNING = function(ENTRY, mechanic, destName, stacks)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        local counter = IncrMechanic(ENTRY, 'WARNING', mechanic)
        SendEvent(Handlers.WARNING, mechanic, name, icon, counter, destName, stacks)
    end,
    
    SPECIAL_WARNING = function(ENTRY, mechanic, destName, stacks)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        local counter = IncrMechanic(ENTRY, 'SPECIAL_WARNING', mechanic)
        SendEvent(Handlers.SPECIAL_WARNING, mechanic, name, icon, counter, destName, stacks)
    end,
    
    PRE_WARNING = function(ENTRY, mechanic, showIn, duration, counter)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        if ENTRY.schedulers[mechanic] then WeakAuras.timer:CancelTimer(ENTRY.schedulers[mechanic]) end
        ENTRY.schedulers[mechanic] = WeakAuras.timer:ScheduleTimer(SendEvent, showIn, Handlers.PRE_WARNING, mechanic, duration or 5, name, icon, counter or 0)
    end,
    
    WARNING_MULTIPLY = function(ENTRY, mechanic, targets)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        SendEvent(Handlers.WARNING_MULTIPLY, mechanic, name, icon, targets)
    end,
    
    COOLDOWN = function(ENTRY, mechanic, duration, sourceName, forceHide, count)
        if not settings.visibility.COOLDOWN then return end
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        local counter = count or IncrMechanic(ENTRY, 'COOLDOWN', mechanic)
        SendEvent(Handlers.COOLDOWN, mechanic, duration, name, icon, counter, sourceName, forceHide)
    end,
    
    TIMER = function(ENTRY, mechanic, duration, destName, stacks, counter)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        SendEvent(Handlers.TIMER, mechanic, duration, name, icon, counter, destName, stacks)
    end,
    
    PHASE = function(ENTRY, mechanic)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        SendEvent(Handlers.PHASE, mechanic, name, icon)
    end,
    
    GTFO = function(ENTRY, mechanic)
        local spellName, icon = GetMechanicInfo(ENTRY, mechanic)
        local name = spellName or CORE.L[mechanic]
        SendEvent(Handlers.GTFO, mechanic, name, icon)
    end,
    
}

CORE.Prototype = function(ENTRY, TYPE, ...)
    
    Prototype[TYPE](ENTRY, ...)
end

CORE.SetDifficulty = function()
    CORE.difficulty = GetInstanceInfo()
    print('Setting Difficulty: ', CORE.difficulty)
end

-- Difficulty Changer
local Dungeon = CreateFrame("Frame")
Dungeon:RegisterEvent("PLAYER_ENTERING_WORLD")
Dungeon:SetScript("OnEvent", function(self, event, ...)
	if event == "PLAYER_ENTERING_WORLD" then
		C_Timer.After(5, function() CORE.SetDifficulty() end)
	end
end)
]]--