local ldb = LibStub("LibDataBroker-1.1")

local faction, localizedFaction = UnitFactionGroup("player")

local Battleground = CreateFrame("Frame", "Broker_Battleground")
local allianceTable = {"Human", "Dwarf", "Gnome", "Night Elf", "Draenei"}
local hordeTable = {"Orc", "Undead", "Troll", "Tauren", "Blood Elf"}
local race = UnitRace("player")
local factionIcon = "interface\\guildframe\\guildlogo-nologo"
local allianceIcon = "interface\\pvpframe\\pvp-currency-alliance"
local hordeIcon = "interface\\pvpframe\\pvp-currency-horde"
if (faction=="Alliance") then factionIcon = allianceIcon elseif (faction=="Horde") then factionIcon = hordeIcon end
local inBG = false
local currentBG = ""
local inQueue = false
local stats = {s = 0, kb = 0, hk = 0, d = 0, h = 0}
local standing = 0
local killBlows = 0
local honorKills = 0
local deaths = 0
local honor = 0

local defaultText = ("|cffe1a500#: |cffffffff"..stats.s.." |cffe1a500KB: |cff00ff00"..stats.kb.." |cffe1a500HK: |cff00ff00"..stats.hk.." |cffe1a500D: |cffff0000"..stats.d.." |cffe1a500H: |cffffffff"..stats.h)

local optionsBackdrop = {
	bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
	edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
	tile = true,
	tileSize = 16,
	edgeSize = 16,
	insets = {left = 4, right = 4, top = 4, bottom = 4}
}

local Broker_Battleground = ldb:NewDataObject("Broker_Battleground", {
	type = "data source",
	text = "No battleground",
	icon = factionIcon,
	label = "Battleground",
	OnClick = function(_, button)
		if button == "LeftButton" then
			if (inBG==true) then
				if (WorldStateScoreFrame:IsVisible()) then
					HideUIPanel(WorldStateScoreFrame)
				else
					ShowUIPanel(WorldStateScoreFrame)
				end
			else
				PVEFrame_ToggleFrame("PVPUIFrame");
			end
		end
	end,
	OnTooltipShow = function(tooltip)
		tooltip:AddLine("Battleground")
		if (inBG==true) then
			tooltip:AddLine(" ")
			tooltip:AddLine(currentBG)
			tooltip:AddLine(" ")
			tooltip:AddLine("|cffffffffPlayer stats:")
			tooltip:AddDoubleLine("Standing:","|cffffffff"..stats.s)
			tooltip:AddDoubleLine("Killing blows:","|cff00ff00"..stats.kb)
			tooltip:AddDoubleLine("Honorable kills:","|cff00ff00"..stats.hk)
			tooltip:AddDoubleLine("Deaths:","|cffff0000"..stats.d)
			tooltip:AddDoubleLine("Bonus honor:","|cffffffff"..stats.h)
			tooltip:AddLine(" ")
			tooltip:AddLine(" ")
			tooltip:AddLine("|cff00ff00Left-Click to toggle score board")
		else 
			tooltip:AddLine(" ")
			tooltip:AddLine("Currently not in a battleground")
			tooltip:AddLine(" ")
			tooltip:AddLine(" ")
			tooltip:AddLine("|cff00ff00Left-Click to toggle PvP Frame")
		end
	end,
})

local function nameUpdate()
	local status, name, id, _, _, teamSize = GetBattlefieldStatus(1)
	if (status=="active") and (teamSize==0) then
		currentBG = name
		inBG = true
	else
		if (UnitInBattleground("player")) then -- Double check!
			currentBG = GetZoneText()
			inBg = true
		else
			currentBG = ""
			Broker_Battleground.text = ("No battleground")
			inBG = false
		end
	end
end

local function statUpdate()
	if (inBG==true) then
		RequestBattlefieldScoreData()
		for i = 1,GetNumBattlefieldScores() do
			local myName = UnitName("player")
			local name, bgKillBlows, bgHonorKills, bgDeaths, bgHonor, faction, race, class, token, dmg, heal = GetBattlefieldScore(i)
			if (name==myName) then
				stats.s = i
				stats.kb = bgKillBlows
				stats.hk = bgHonorKills
				stats.d = bgDeaths
				stats.h = math.floor(bgHonor)
			end
		end
		Broker_Battleground.text = ("|cffe1a500#: |cffffffff"..stats.s.." |cffe1a500KB: |cff00ff00"..stats.kb.." |cffe1a500HK: |cff00ff00"..stats.hk.." |cffe1a500D: |cffff0000"..stats.d.." |cffe1a500H: |cffffffff"..stats.h)
	else
		stats.standing = 1
		stats.killBlows = 0
		stats.honorKills = 0
		stats.deaths = 0
		stats.honor = 0
		Broker_Battleground.text = ("No battleground")
	end
end

local lastUpdate = 0
local OnUpdate = CreateFrame("Frame")
OnUpdate:SetScript("OnUpdate", function(self, elapsed)
	lastUpdate = lastUpdate + elapsed
	if (lastUpdate>1) then
		if (inBG==true) then
			RequestBattlefieldScoreData()
		end
		if (queued==true) then
		
		end
		lastUpdate = lastUpdate - elapsed
	end
end)

local OnEvent = CreateFrame("Frame")
OnEvent:RegisterEvent("ADDON_LOADED")
OnEvent:RegisterEvent("PLAYER_ENTERING_WORLD")
OnEvent:RegisterEvent("PLAYER_ENTERING_BATTLEGROUND")
OnEvent:RegisterEvent("PLAYER_DEAD")
OnEvent:SetScript("OnEvent", function(self, event, addon, ...)
	if (event=="ADDON_LOADED") then
	
	elseif (event=="PLAYER_ENTERING_WORLD") then
		nameUpdate()
		statUpdate()
	elseif (event=="PLAYER_ENTERING_BATTLEGROUND") then
		nameUpdate()
		statUpdate()
		inBG = true
	elseif (event=="PLAYER_PVP_KILLS_CHANGED") then
		statUpdate()
	elseif (event=="UPDATE_BATTLEFIELD_SCORE") then
		nameUpdate()
		statUpdate()
	elseif (event=="PLAYER_DEAD") then		
		statUpdate()
	end
end)
OnEvent:RegisterEvent("PLAYER_PVP_KILLS_CHANGED")
OnEvent:RegisterEvent("UPDATE_BATTLEFIELD_SCORE")
OnEvent:RegisterEvent("UPDATE_BATTLEFIELD_STATUS")



