local L = LibStub("AceLocale-3.0"):GetLocale("Altoholic")

local INFO_REALM_LINE = 0
local INFO_CHARACTER_LINE = 1
local INFO_TOTAL_LINE = 2

local WHITE		= "|cFFFFFFFF"
local GREEN		= "|cFF00FF00"
local YELLOW	= "|cFFFFFF00"
local GREY		= "|cFF808080"
local GOLD		= "|cFFFFD700"
local RED		= "|cFFFF0000"

local ICON_FACTION_HORDE = "Interface\\Icons\\INV_BannerPVP_01"
local ICON_FACTION_ALLIANCE = "Interface\\Icons\\INV_BannerPVP_02"

Altoholic.Activity = {}

function Altoholic.Activity:Update()
	local VisibleLines = 14
	local frame = "AltoholicFrameActivity"
	local entry = frame.."Entry"
	
	local Characters = Altoholic.Characters
	
	local DS = DataStore
	
	local offset = FauxScrollFrame_GetOffset( _G[ frame.."ScrollFrame" ] );
	local DisplayedCount = 0
	local VisibleCount = 0
	local DrawRealm
	local CurrentAccount, CurrentRealm
	local i=1
	
	for _, line in pairs(Characters:GetView()) do
		local s = Characters:Get(line)
		local lineType = mod(s.linetype, 3)
		
		if (offset > 0) or (DisplayedCount >= VisibleLines) then		-- if the line will not be visible
			if lineType == INFO_REALM_LINE then								-- then keep track of counters
				CurrentAccount = s.account
				CurrentRealm = s.realm
				if s.isCollapsed == false then
					DrawRealm = true
				else
					DrawRealm = false
				end
				VisibleCount = VisibleCount + 1
				offset = offset - 1		-- no further control, nevermind if it goes negative
			elseif DrawRealm then
				VisibleCount = VisibleCount + 1
				offset = offset - 1		-- no further control, nevermind if it goes negative
			end
		else		-- line will be displayed
			if lineType== INFO_REALM_LINE then
				CurrentAccount = s.account
				CurrentRealm = s.realm
				if s.isCollapsed == false then
					_G[ entry..i.."Collapse" ]:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Up"); 
					DrawRealm = true
				else
					_G[ entry..i.."Collapse" ]:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up");
					DrawRealm = false
				end
				_G[entry..i.."Collapse"]:Show()
				_G[entry..i.."Name"]:SetWidth(300)
				_G[entry..i.."Name"]:SetPoint("TOPLEFT", 25, 0)
				_G[entry..i.."NameNormalText"]:SetWidth(300)
				if s.account == "Default" then	-- saved as default, display as localized.
					_G[entry..i.."NameNormalText"]:SetText(format("%s (%s".. L["Account"]..": %s%s|r)", s.realm, WHITE, GREEN, L["Default"]))
				else
					local last = Altoholic:GetLastAccountSharingInfo(CurrentRealm, CurrentAccount)
					_G[entry..i.."NameNormalText"]:SetText(format("%s (%s".. L["Account"]..": %s%s %s%s|r)", s.realm, WHITE, GREEN, s.account, YELLOW, last or ""))
				end				
				_G[entry..i.."Level"]:SetText("")
				_G[entry..i.."MailsNormalText"]:SetText("")
				_G[entry..i.."LastMailCheckNormalText"]:SetText("")
				_G[entry..i.."AuctionsNormalText"]:SetText("")
				_G[entry..i.."BidsNormalText"]:SetText("")
				_G[entry..i.."LastAHCheckNormalText"]:SetText("")
				_G[entry..i.."LastLogoutNormalText"]:SetText("")
				
				_G[ entry..i ]:SetID(line)
				_G[ entry..i ]:Show()
				i = i + 1
				VisibleCount = VisibleCount + 1
				DisplayedCount = DisplayedCount + 1
			elseif DrawRealm then
				if (lineType == INFO_CHARACTER_LINE) then
					local character = DS:GetCharacter(s.name, CurrentRealm, CurrentAccount)
					
					local icon
					if DS:GetCharacterFaction(character) == "Alliance" then
						icon = Altoholic:TextureToFontstring(ICON_FACTION_ALLIANCE, 18, 18) .. " "
					else
						icon = Altoholic:TextureToFontstring(ICON_FACTION_HORDE, 18, 18) .. " "
					end
					
					_G[entry..i.."Collapse"]:Hide()
					_G[entry..i.."Name"]:SetWidth(170)
					_G[entry..i.."Name"]:SetPoint("TOPLEFT", 10, 0)
					_G[entry..i.."NameNormalText"]:SetWidth(170)
					_G[entry..i.."NameNormalText"]:SetText(icon .. format("%s (%s)", DS:GetColoredCharacterName(character), DS:GetCharacterClass(character)))
					_G[entry..i.."Level"]:SetText(GREEN .. DS:GetCharacterLevel(character))
				
					local num = DS:GetNumMails(character)
					if num == 0 then
						_G[entry..i.."MailsNormalText"]:SetText(GREY .. "0")
					else
						local color = GREEN		-- green by default, red if at least one mail is about to expire
						
						local threshold = Altoholic.Options:Get("MailWarningThreshold")
						if DS:GetNumExpiredMails(character, threshold) > 0 then
							color = RED
						end
					
						_G[entry..i.."MailsNormalText"]:SetText(color .. num)
					end
					
					local lastVisit = DS:GetMailboxLastVisit(character)
					_G[entry..i.."LastMailCheckNormalText"]:SetText(WHITE .. Altoholic:FormatDelay(lastVisit))
					
					num = DS:GetNumAuctions(character)
					_G[entry..i.."AuctionsNormalText"]:SetText(((num == 0) and GREY or GREEN) .. num)

					num = DS:GetNumBids(character)
					_G[entry..i.."BidsNormalText"]:SetText(((num == 0) and GREY or GREEN) .. num)
					
					lastVisit = DS:GetAuctionHouseLastVisit(character)
					_G[entry..i.."LastAHCheckNormalText"]:SetText(WHITE .. Altoholic:FormatDelay(lastVisit))

					if (s.name == UnitName("player")) and (CurrentRealm == GetRealmName()) and (CurrentAccount == "Default") then
						_G[entry..i.."LastLogoutNormalText"]:SetText(GREEN .. GUILD_ONLINE_LABEL)
					else
						_G[entry..i.."LastLogoutNormalText"]:SetText(WHITE .. Altoholic:FormatDelay(DS:GetLastLogout(character)))
					end
				elseif (lineType == INFO_TOTAL_LINE) then
					_G[entry..i.."Collapse"]:Hide()
					_G[entry..i.."Name"]:SetWidth(200)
					_G[entry..i.."Name"]:SetPoint("TOPLEFT", 15, 0)
					_G[entry..i.."NameNormalText"]:SetWidth(200)
					_G[entry..i.."NameNormalText"]:SetText(L["Totals"])
					_G[entry..i.."Level"]:SetText(s.level)
					_G[entry..i.."MailsNormalText"]:SetText("")
					_G[entry..i.."LastMailCheckNormalText"]:SetText("")
					_G[entry..i.."AuctionsNormalText"]:SetText("")
					_G[entry..i.."BidsNormalText"]:SetText("")
					_G[entry..i.."LastAHCheckNormalText"]:SetText("")
					_G[entry..i.."LastLogoutNormalText"]:SetText("")
				end
				_G[ entry..i ]:SetID(line)
				_G[ entry..i ]:Show()
				i = i + 1
				VisibleCount = VisibleCount + 1
				DisplayedCount = DisplayedCount + 1
			end
		end
	end
	
	while i <= VisibleLines do
		_G[ entry..i ]:SetID(0)
		_G[ entry..i ]:Hide()
		i = i + 1
	end

	FauxScrollFrame_Update( _G[ frame.."ScrollFrame" ], VisibleCount, VisibleLines, 18);
end	

function Altoholic.Activity:OnEnter(self)
	local line = self:GetParent():GetID()
	local s = Altoholic.Characters:Get(line)
	
	if mod(s.linetype, 3) ~= INFO_CHARACTER_LINE then		
		return
	end
	
	local DS = DataStore
	local character = DS:GetCharacter(Altoholic.Characters:GetInfo(line))
	
	AltoTooltip:ClearLines();
	AltoTooltip:SetOwner(self, "ANCHOR_RIGHT");
	
	AltoTooltip:AddDoubleLine(DS:GetColoredCharacterName(character), DS:GetColoredCharacterFaction(character))
	AltoTooltip:AddLine(format("%s %s |r%s %s", L["Level"], 
		GREEN..DS:GetCharacterLevel(character), DS:GetCharacterRace(character),	DS:GetCharacterClass(character)),1,1,1)

	local zone, subZone = DS:GetLocation(character)
	AltoTooltip:AddLine(format("%s: %s |r(%s|r)", L["Zone"], GOLD..zone, GOLD..subZone),1,1,1)
	
	AltoTooltip:AddLine(EXPERIENCE_COLON .. " " 
				.. GREEN .. DS:GetXP(character) .. WHITE .. "/" 
				.. GREEN .. DS:GetXPMax(character) .. WHITE .. " (" 
				.. GREEN .. DS:GetXPRate(character) .. "%"
				.. WHITE .. ")",1,1,1);	
	
	local restXP = DS:GetRestXP(character)
	if restXP and restXP > 0 then
		AltoTooltip:AddLine(format("%s: %s", L["Rest XP"], GREEN..restXP),1,1,1)
	end

	AltoTooltip:AddLine(" ",1,1,1);
	AltoTooltip:AddLine(GOLD..CURRENCY..":",1,1,1);
	
	for i = 1, DS:GetNumCurrencies(character) do
		local isHeader, name, count = DS:GetCurrencyInfo(character, i)
		if isHeader then
			AltoTooltip:AddLine(YELLOW..name)
		else
			AltoTooltip:AddLine(format("  %s: %s", name, GREEN..count),1,1,1);
		end
	end
	
	if DS:GetNumCurrencies(character) == 0 then
		AltoTooltip:AddLine(WHITE..NONE,1,1,1);
	end
	
	AltoTooltip:Show();
end

local VIEW_MAILS = 3
local VIEW_AUCTIONS = 5
local VIEW_BIDS = 6

function Altoholic.Activity:OnClick(self)
	local line = self:GetParent():GetID()
	local s = Altoholic.Characters:Get(line)
	
	if mod(s.linetype, 3) ~= INFO_CHARACTER_LINE then		
		return
	end
	
	local id = self:GetID()
	if (id == 2) or (id >= 5) then	-- exit if it's not the right column
		return
	end
	
	Altoholic:SetCurrentCharacter( Altoholic.Characters:GetInfo(line) )
	
	local DS = DataStore
	local character = DS:GetCharacter(Altoholic.Characters:GetInfo(line))
	
	local action
	
	if id == 1 then			-- mails
		if DS:GetNumMails(character) > 0 then				-- only set the action if there are data to show
			action = VIEW_MAILS
		end
	elseif id == 3 then		-- auctions
		if DS:GetNumAuctions(character) > 0 then
			action = VIEW_AUCTIONS
		end
	elseif id == 4 then		-- bids
		if DS:GetNumBids(character) > 0 then
			action = VIEW_BIDS
		end
	end
	
	if action then
		Altoholic.Tabs.Characters:SetCurrent( Altoholic:GetCurrentCharacter() )
		Altoholic.Tabs:OnClick(2)
		Altoholic.Tabs.Characters:ViewCharInfo(action)	
	end
end
