--[[
  * DebugTest
  * Author: Sasky
  GetGuildId(luaindex index)
  GetNumGuilds()
  GetNumGuildMembers(integer guildId)
  SetGuildMemberNote(integer guildId, luaindex memberIndex, string note)
  GetGuildMemberInfo
	playerStatus: 1 online, 4 offline
]]--

zdb = {}

zdb.ui = {}
zdb.color = "EEEEEE"

zdb.ui.clickHandler = function()
	d(GuildCharNames:generateLink(data))
end

zdb.linkHandler = function(rawLink, _, _, _, linkType, varargs)
    --d("Link type: " .. linkType .. " / Args: " .. varargs)
    d(rawLink:gsub("|","---"))
end

function bl(val)
	if val == nil then return "NIL" elseif val then return "T" else return "F" end
end

AllianceColor = {}
AllianceColor[ALLIANCE_ALDMERI_DOMINION] = "|cB2B222" --AD
AllianceColor[ALLIANCE_EBONHEART_PACT] = "|cB22222" --EP
AllianceColor[ALLIANCE_DAGGERFALL_COVENANT] = "|c6666EE" --DC

local function formatTime(delta)
    local sec = delta % 60
    delta = (delta - sec) / 60
    local min = delta % 60
    local hrs = (delta - min) / 60

    local out = ""
    if hrs > 0 then
        out = out .. hrs .. "h "
    end
    out = out .. min .. "m " .. sec .. "s"
    return out
end

function updateUI()
    local cID = GetCurrentCampaignId()
    local time = formatTime(GetSecondsUntilCampaignScoreReevaluation(cID))
    zdbDebugTestTime:SetText(time)
    zdbDebugTestAD:SetText("+" .. GetCampaignAlliancePotentialScore(cID, ALLIANCE_ALDMERI_DOMINION))
    zdbDebugTestDC:SetText("+" .. GetCampaignAlliancePotentialScore(cID, ALLIANCE_DAGGERFALL_COVENANT))
    zdbDebugTestEP:SetText("+" ..  GetCampaignAlliancePotentialScore(cID, ALLIANCE_EBONHEART_PACT))
end

SLASH_COMMANDS["/zdb"] = function()
    EVENT_MANAGER:RegisterForUpdate("ZDBUpdateAPCount", 1000, updateUI)
end

SLASH_COMMANDS["/linkdb"] = function()
    LINK_HANDLER:RegisterCallback(LINK_HANDLER.LINK_CLICKED_EVENT, zdb.linkHandler)
end


function nn(val)
	if val == nil then return "NIL" end
	return val
end

zdb.dumpInfo = function(_, _, _, _, linkType, varargs)
	if linkType ~= "playerDetail" then return false end
	d(nn(d1))
	zdbDebugTestName:SetText(nn(d1))
	return true
end

CyrHUD = {}

CyrHUD.info = {}
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION] = {}
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION].color = { hex = "B2B222", r = .698, g = .698, b = .133 }
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION][KEEPTYPE_KEEP] = {}
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION][KEEPTYPE_KEEP].icon = "/esoui/art/mappins/ava_largekeep_aldmeri.dds"
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION][KEEPTYPE_KEEP].iconua = "/esoui/art/mappins/ava_largekeep_aldmeri_underattack.dds"
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION][KEEPTYPE_OUTPOST] = {}
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION][KEEPTYPE_OUTPOST].icon = "/esoui/art/mappins/ava_outpost_aldmeri.dds"
CyrHUD.info[ALLIANCE_ALDMERI_DOMINION][KEEPTYPE_OUTPOST].iconua = "/esoui/art/mappins/ava_outpost_aldmeri.dds"
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT] = {}
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT].color = { hex = "6666EE", r = .4, g = .4, b = .933 }
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT][KEEPTYPE_KEEP] = {}
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT][KEEPTYPE_KEEP].icon = "/esoui/art/mappins/ava_largekeep_daggerfall.dds"
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT][KEEPTYPE_KEEP].iconua = "/esoui/art/mappins/ava_largekeep_daggerfall_underattack.dds"
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT][KEEPTYPE_OUTPOST] = {}
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT][KEEPTYPE_OUTPOST].icon = "/esoui/art/mappins/ava_outpost_daggerfall.dds"
CyrHUD.info[ALLIANCE_DAGGERFALL_COVENANT][KEEPTYPE_OUTPOST].iconua = "/esoui/art/mappins/ava_outpost_daggerfall.dds"
CyrHUD.info[ALLIANCE_EBONHEART_PACT] = {}
CyrHUD.info[ALLIANCE_EBONHEART_PACT].color = { hex = "B22222", r = .698, g = .133, b = .133 }
CyrHUD.info[ALLIANCE_EBONHEART_PACT][KEEPTYPE_KEEP] = {}
CyrHUD.info[ALLIANCE_EBONHEART_PACT][KEEPTYPE_KEEP].icon = "/esoui/art/mappins/ava_largekeep_ebonheart.dds"
CyrHUD.info[ALLIANCE_EBONHEART_PACT][KEEPTYPE_KEEP].iconua = "/esoui/art/mappins/ava_largekeep_ebonheart_underattack.dds"
CyrHUD.info[ALLIANCE_EBONHEART_PACT][KEEPTYPE_OUTPOST] = {}
CyrHUD.info[ALLIANCE_EBONHEART_PACT][KEEPTYPE_OUTPOST].icon = "/esoui/art/mappins/ava_outpost_ebonheart.dds"
CyrHUD.info[ALLIANCE_EBONHEART_PACT][KEEPTYPE_OUTPOST].iconua = "/esoui/art/mappins/ava_outpost_ebonheart.dds"



CyrHUD.entryCount = 0
CyrHUD.entries = {}
CyrHUD.createEntry = function()
    local num = CyrHUD.entryCount + 1
    local yoff = num*35-5
    CyrHUD.entryCount = num
    local entry = {}
    local entryName = "CyrHUDEntry" .. num
    entry.main = WINDOW_MANAGER:CreateControl(entryName .. "main", zdbDebugTest, CT_BACKDROP)
    entry.main:SetDimensions(280, 35)
    entry.main:SetAnchor(TOPLEFT, zdbDebugTest, TOPLEFT, 0, yoff)
    entry.main:SetCenterColor( 0, 0, 0, .3 )
    entry.main:SetEdgeColor( 0, 0, 0, 0 )

    entry.icon = WINDOW_MANAGER:CreateControl(entryName .. "icon", zdbDebugTest, CT_TEXTURE)
    entry.icon:SetAnchor(TOPLEFT, entry.main, TOPLEFT, -2, -2)
    entry.icon:SetDimensions(40,40)

    local fontMain = "EsoUI/Common/Fonts/univers67.otf|18|soft-shadow-thick"
    entry.name = WINDOW_MANAGER:CreateControl(entryName .. "name", zdbDebugTest, CT_LABEL)
    entry.name:SetDimensions(150,30)
    entry.name:SetAnchor(TOPLEFT, entry.main, TOPLEFT, 35, 5)
    entry.name:SetFont(fontMain)

    local fontSmall = "EsoUI/Common/Fonts/univers67.otf|14|soft-shadow-thin"
    entry.defSiege = WINDOW_MANAGER:CreateControl(entryName .. "defSiege", zdbDebugTest, CT_LABEL)
    entry.defSiege:SetDimensions(30,30)
    entry.defSiege:SetAnchor(TOPLEFT, entry.main, TOPLEFT, 220, 5)
    entry.defSiege:SetFont(fontMain)

    entry.attSiege = WINDOW_MANAGER:CreateControl(entryName .. "attSiege", zdbDebugTest, CT_LABEL)
    entry.attSiege:SetDimensions(30,30)
    entry.attSiege:SetAnchor(TOPLEFT, entry.main, TOPLEFT, 190, 5)
    entry.attSiege:SetFont(fontMain)

    entry.time = WINDOW_MANAGER:CreateControl(entryName .. "time", zdbDebugTest, CT_LABEL)
    entry.time:SetDimensions(30,30)
    entry.time:SetAnchor(TOPLEFT, entry.main, TOPLEFT, 250, 5)
    entry.time:SetFont(fontMain)
    entry.time:SetColor(.8,.8,.8)

    table.insert(CyrHUD.entries, entry)
    return entry
end

CyrHUD.getEntry = function()
    CyrHUD.ptr = CyrHUD.ptr + 1
    if #CyrHUD.entries < CyrHUD.ptr then
        CyrHUD.createEntry()
    end
    CyrHUD.entries[CyrHUD.ptr].main:SetHidden(false)
    CyrHUD.entries[CyrHUD.ptr].icon:SetHidden(false)
    CyrHUD.entries[CyrHUD.ptr].name:SetHidden(false)
    CyrHUD.entries[CyrHUD.ptr].defSiege:SetHidden(false)
    CyrHUD.entries[CyrHUD.ptr].attSiege:SetHidden(false)
    CyrHUD.entries[CyrHUD.ptr].time:SetHidden(false)
    return CyrHUD.entries[CyrHUD.ptr]
end

CyrHUD.ptr = 0
CyrHUD.reset = function()
    for _,p in pairs(CyrHUD.entries) do
        p.main:SetHidden(true)
        p.icon:SetHidden(true)
        p.name:SetHidden(true)
        p.defSiege:SetHidden(true)
        p.attSiege:SetHidden(true)
        p.time:SetHidden(true)
    end
    CyrHUD.ptr = 0
end

CyrHUD.battles = {}
CyrHUD.add = function(keepID)
    if CyrHUD.battles[keepID] == nil then
        d("Adding " .. GetKeepName(keepID))
        CyrHUD.battles[keepID] = CyrHUD.Battle(keepID)
    end
end

CyrHUD.checkAdd = function(keepID)
    if CyrHUD.battles[keepID] == nil then
        local battle = CyrHUD.Battle(keepID)
        if battle:isBattle() then
            CyrHUD.battles[keepID] = battle
        end
    end
end

CyrHUD.updateAll = function()
    for i,_ in pairs(CyrHUD.battles) do
        --Update in-place
        CyrHUD.battles[i]:update()
    end
end

CyrHUD.printAll = function()
    CyrHUD.reset()
    for _,b in pairs(CyrHUD.battles) do
        CyrHUD.print(b)
    end
end

CyrHUD.print = function(battle)
    entry = CyrHUD.getEntry()
    entry.icon:SetTexture(battle:getIcon())
    entry.name:SetText(battle.keepName)
    local color = CyrHUD.info[battle.defender].color
    entry.name:SetColor(color.r, color.g, color.b)
    entry.time:SetText(battle:getDuration())
    local ds, dc = battle:getDefSiege()
    entry.defSiege:SetText(ds)
    entry.defSiege:SetColor(dc.r, dc.g, dc.b)
    local as, ac = battle:getAttSiege()
    entry.attSiege:SetText(as)
    entry.attSiege:SetColor(ac.r, ac.g, ac.b)
    local r,g,b,a = battle:getBGColor()
    entry.main:SetCenterColor(r,g,b,a)
    --entry.defSiege:SetText()
end

------------------------------------------------------------------------
-- Battle class
------------------------------------------------------------------------
CyrHUD.Battle = {}
CyrHUD.Battle.__index = CyrHUD.Battle

setmetatable(CyrHUD.Battle, {
    __call = function (cls, ...)
        return cls.new(...)
    end,
})

CyrHUD.Battle.new = function(keepID)
    local _, bc = GetKeepKeysByIndex(10)
    local self = setmetatable({}, CyrHUD.Battle)
    self.startBattle = GetTimeStamp()
    self.endBattle = nil
    self.keepID = keepID
    self.keepName = GetKeepName(keepID)
    self.keepType = GetKeepType(keepID)
    self:update()
    return self
end

function CyrHUD.Battle:update()
    local _, bc = 2,2 -- GetKeepKeysByIndex(10)
    self.defender = GetKeepAlliance(self.keepID, bc)
    self.keepUA = GetKeepUnderAttack(self.keepID, bc)
    self.siege = {}
    self.siege[ALLIANCE_ALDMERI_DOMINION] = GetNumSieges(self.keepID, bc, ALLIANCE_ALDMERI_DOMINION)
    self.siege[ALLIANCE_DAGGERFALL_COVENANT] = GetNumSieges(self.keepID, bc, ALLIANCE_DAGGERFALL_COVENANT)
    self.siege[ALLIANCE_EBONHEART_PACT] = GetNumSieges(self.keepID, bc, ALLIANCE_EBONHEART_PACT)

    if not self:isBattle() then
        if self.endBattle then
            --Remove after time
            if GetDiffBetweenTimeStamps(GetTimeStamp(), self.endBattle) > 15 then
                CyrHUD.battles[self.keepID] = nil
            end
        else
            self.endBattle = GetTimeStamp()
        end
    end
end

function CyrHUD.Battle:getBGColor()
    if self.endBattle then
        if self.defender == GetUnitAlliance("player") then
            return .2,.5,.2,.6
        end
        return .5,.5,.5,.3
    end
    local delta = GetDiffBetweenTimeStamps(GetTimeStamp(), self.startBattle)
    if delta < 60 then
        return (60-delta)/120,0,0,.3
    end

    return 0,0,0,.3
end

function CyrHUD.Battle:getDuration()
    local time = self.endBattle or GetTimeStamp()
    local delta = GetDiffBetweenTimeStamps(time, self.startBattle)
    delta = math.floor(delta/60)
    if delta == 0 then return "" end
    local min = delta % 60
    local hrs = (delta - min) / 60

    local out = ""
    if hrs > 0 then
        out = out .. hrs .. "h "
    end
    out = out .. min .. "m "
    return out
end

function CyrHUD.Battle:getDefSiege()
    local siege = self.siege[self.defender]
    --d(self.keepName .. ":" ..  siege .. " (" .. self.defender .. ")")
    if siege == 0 then siege = "" end
    return siege, CyrHUD.info[self.defender].color
end

function CyrHUD.Battle:getAttSiege()
    local siege = self.siege
    siege[self.defender] = nil
    local count, faction = 0, nil
    for f,c in pairs(siege) do
        count = count + c
        if c > 0 then
            if faction == nil then
                faction = f
            else
                faction = 0
            end
        end
    end
    local color = { hex = "CCCCCC", r=.8, g=.8, b=.8 }
    if faction and faction ~= 0 then
        color = CyrHUD.info[faction].color
    end
    if count == 0 then count = "" end
    return count, color
end

function CyrHUD.Battle:isBattle()
    if self.keepUA then return true end
    local count = (self.siege[ALLIANCE_ALDMERI_DOMINION] + self.siege[ALLIANCE_DAGGERFALL_COVENANT] + self.siege[ALLIANCE_EBONHEART_PACT])
    return count > 0
end

function CyrHUD.Battle:getIcon()
    if self.keepUA then
        return CyrHUD.info[self.defender][self.keepType].iconua
    else
        return CyrHUD.info[self.defender][self.keepType].icon
    end
end

function bl(val) if val then return "T" end return "F" end

SLASH_COMMANDS["/zdb2"] = function(i)
    d("Local campaign: " .. GetCurrentCampaignId())
    local kid, bc = GetKeepKeysByIndex(i)
    d(nn(i) .. ":" .. nn(bc) .. "/" .. nn(kid) .. " " .. nn(GetKeepName(kid)))
    d("Under attack? " .. bl(GetKeepUnderAttack(kid, bc)))
    d("Siege EP:" .. GetNumSieges(kid, bc, ALLIANCE_EBONHEART_PACT) .. " DC:" .. GetNumSieges(kid, bc, ALLIANCE_DAGGERFALL_COVENANT) .. " AD:" .. GetNumSieges(kid, bc, ALLIANCE_ALDMERI_DOMINION))
end

CyrHUD.scanKeeps = function()
    for i=3,20 do
        CyrHUD.checkAdd(i)
    end
end

local function init()
    d("Adding keep info")
    EVENT_MANAGER:RegisterForUpdate("CyrHUBKeepCheck", 5000, function()
        CyrHUD.scanKeeps()
    end)
    EVENT_MANAGER:RegisterForUpdate("CyrHUBUIUpdate", 1000, function()
        CyrHUD.updateAll()
        CyrHUD.printAll()
    end)
    EVENT_MANAGER:RegisterForUpdate("ZDBUpdateAPCount", 1000, updateUI)
end

local showCyrHUD = false
SLASH_COMMANDS["/cyrhud"] = function()
    if showCyrHUD then
        EVENT_MANAGER:UnregisterForUpdate("CyrHUBKeepCheck")
        EVENT_MANAGER:UnregisterForUpdate("CyrHUBUIUpdate")
        EVENT_MANAGER:UnregisterForUpdate("ZDBUpdateAPCount")
        WYK_QuestTracker_MQT:SetAlpha(1)
        zdbDebugTest:SetHidden(true)
        showCyrHUD = false
    else
        WYK_QuestTracker_MQT:SetAlpha(0)
        zdbDebugTest:SetHidden(false)
        init()
        showCyrHUD = true
    end
end