local TOCNAME,RTC = ...
local L = setmetatable({}, {__index = function (t, k)  
	L=RTC.L
	return RTC.L[k]
end})

RollTrackerClassic_Addon=RTC

--[[
	RollTracker Classic 
	1.72
		- bugfix
		- Commands "/rt raidroll" & "/rt raidroll list"
		
	1.71
		- bugfix
		
	1.70
		- fix priest icon
		- Export-Button for CSV
		- About-Panel		
	
	1.64
		- whitelist
		- Option LootTracker "Enable"
		- Option LootTracker "Maximum stored loot"
		- Option LootTracker "Small font"
		- Option LootTracker "Show item icon"		
	
	1.63
		- track on ItemType
		- change jokers to %joker%
		- option track solo/group/raid<=10/raid>10
		- option ShortMessage
		
	1.62
		- workaround for a bug
		- improvments for loot-tracker
	
	1.61
		- use hooksecurefunc for clearloots
		- include LootTracker and CSV Export
		
		

	based on RollTracker Lite v0.4 - by Jerry Chong. <zanglang@gmail.com>
	Originally written by Coth of Gilneas and Morodan of Khadgar.
	Russian translation by tierggg and Hubbotu
	
	TODO 
		- timer für ausblenden.

]]--

RTC.OnDebug=true


RTC.Version=GetAddOnMetadata(TOCNAME, "Version") 
RTC.Title= (GetLocale() == "zhTW") and "骰子記錄" or GetAddOnMetadata(TOCNAME, "Title") 

RTC.MAXRARITY=6
RTC.IconDice= "Interface\\Buttons\\UI-GroupLoot-Dice-Up"
RTC.IconGreed= "Interface\\Buttons\\UI-GroupLoot-Coin-Up"
RTC.IconPass= "Interface\\Buttons\\UI-GroupLoot-Pass-Up"
RTC.IconLoot= "Interface\\GroupFrame\\UI-Group-MasterLooter"
RTC.TxtEscapePicture="|T%s:0|t"
RTC.TxtEscapeIcon="|T%s:0:0:0:0:64:64:4:60:4:60|t"

RTC.MSGPREFIX="RTC: "
RTC.MSGPREFIX_START="RTC.StartRoll: "
RTC.LootHistoryCloseTimerTIME=5
RTC.LOOTTRACKER_MAXLINES=1000


function RTC.GetPlayerList(unsort)
	local count,start
	local prefix
	local localizedClass, englishClass, classIndex
	local ret={}
	local retName={}
		
	if IsInRaid() then
		prefix="raid"
		count=MAX_RAID_MEMBERS
		start=1
	else
		prefix="party"
		count=MAX_PARTY_MEMBERS
		start=0
	end
	
	
	
	for index = start,count do
		local name=""
		if index>0 then
			name=GetUnitName(prefix..index)
			localizedClass, englishClass, classIndex = UnitClass(prefix..index)
		else
			name=GetUnitName("player")
			localizedClass, englishClass, classIndex = UnitClass("player")
		end

		if name~=nil then
			local entry={
				["name"]=name,
				["class"]=englishClass,
				}
			tinsert(ret,entry)
			retName[name]=entry
		end
		
	end
	
	--[[
	if isDebug then
		for i=1,39 do
			local name="Very Long Dummy Charakter Name"..i
			local entry={
				["name"]=name,
				["class"]="PRIEST",
				}
			tinsert(ret,entry)
			retName[name]=entry
		end
	end
	--]]
	
	if unsort then
		sort(ret,function(a,b) return (a.class<b.class or (a.class==b.class and a.name < b.name)) end)
	end

	return ret,retName
end

function RTC.PopupMinimap(frame)
	RTC.PopupDynamic:Wipe()
	RTC.PopupDynamic:AddItem(L["BtnRoll"],nil,false,RTC.BtnRoll)
	if RollTrackerClassicDB.NeedAndGreed then
		RTC.PopupDynamic:AddItem(L["BtnGreed"],nil,false,RTC.BtnGreed)
	end
	RTC.PopupDynamic:AddItem(L["BtnPass"],nil,false,RTC.BtnPass)
	RTC.PopupDynamic:AddItem("",nil,true)
	RTC.PopupDynamic:AddItem(L["BtnRaidRoll"],nil,false,RTC.RaidRoll)
	RTC.PopupDynamic:AddItem("",nil,true)
	
	RTC.PopupDynamic:AddItem(L["BtnOpen"],nil,false,RTC.ShowWindow,1)
	if RollTrackerClassicDB.LootTracker.Enable then
		RTC.PopupDynamic:AddItem(L["BtnOpenLoot"],nil,false,RTC.ShowWindow,2)	
		RTC.PopupDynamic:AddItem(L["BtnCSVExport"],nil,false,RTC.ShowWindow,3)	
	end
	RTC.PopupDynamic:AddItem(L["BtnLootRolls"],nil,false,RTC.LootHistoryShow)
	RTC.PopupDynamic:AddItem("",nil,true)
	RTC.PopupDynamic:AddItem(L["BtnConfig"],nil,false,RTC.Options.Open,RTC.Options)
	RTC.PopupDynamic:AddItem(L["PanelAbout"],nil,false,RTC.Options.Open,RTC.Options,4)
	
	RTC.PopupDynamic:AddItem("",nil,true)
	
	RTC.PopupDynamic:AddItem(L["CboxLTEnable"],RollTrackerClassicDB.LootTracker.Enable,false,RollTrackerClassicDB.LootTracker,"Enable")
	
	RTC.PopupDynamic:AddItem("",nil,true)
	RTC.PopupDynamic:AddItem(L["BtnCancel"],nil,false)
	
	RTC.PopupDynamic:Show(frame)
end

function RTC.GetAutoChannel ()
	-- Return an appropriate channel in order of preference: /raid, /p, /s
	local channel
	if IsInRaid() then
		channel = "RAID"
	elseif IsInGroup() then
		channel = "PARTY"
	else 
		channel = "SAY"
	end
	return channel
end

function RTC.AddChat(msg)
	if msg then
		if IsInGroup() or IsInRaid() then
			SendChatMessage(msg , RTC.GetAutoChannel())
		else
			DEFAULT_CHAT_FRAME:AddMessage(msg)
		end
	end
end


-- LootHistory
local function MyLootHistoryFrame_FullUpdate(self)
	local numItems = C_LootHistory.GetNumItems()	
	for i=1,numItems do
		if self.itemFrames[i] and self.itemFrames[i].rollID and RTC.LootHistoryCleardRollID[self.itemFrames[i].rollID]  then
			self.itemFrames[i]:Hide()
		end
	end
end

function RTC.LootHistoryClear()
	if RTC.LootHistroyFrameHooked==nil then
		RTC.LootHistroyFrameHooked=true
		hooksecurefunc("LootHistoryFrame_FullUpdate",MyLootHistoryFrame_FullUpdate)
	end
	
	local numItems = C_LootHistory.GetNumItems()
	
	for i=1,numItems do
		if LootHistoryFrame.itemFrames[i] then 
			RTC.LootHistoryCleardRollID[LootHistoryFrame.itemFrames[i].rollID]=true			
		end
	end
		
	LootHistoryFrame_FullUpdate(LootHistoryFrame)
end

function RTC.LootHistoryShow(rollID)
	if not LootHistoryFrame:IsShown() or rollID==nil then
		ToggleLootHistoryFrame()
	end
	if rollID then 
		LootHistoryFrame.expandedRolls[rollID] = true
		LootHistoryFrame_FullUpdate(LootHistoryFrame)
	end	
end

-- GUI

function RTC.ResetWindow()
	RollTrackerClassicMainWindow:ClearAllPoints()
	RollTrackerClassicMainWindow:SetPoint("Center", UIParent, "Center", 0, 0)
	RollTrackerClassicMainWindow:SetWidth(200)
	RollTrackerClassicMainWindow:SetHeight(200)
	RTC.SaveAnchors()
	RTC.ShowWindow(1)
end

function RTC.ToggleWindow(id)
	if RollTrackerClassicMainWindow:IsVisible() then
		RTC.HideWindow()
	else
		RTC.ShowWindow(id)
	end
end

function RTC.MenuButtonClick(self,button)
	if button=="LeftButton" then 
		if IsShiftKeyDown() then
			RTC.LootHistoryShow()
		else
			RTC.ToggleWindow()
		end
		
	else
		if self.isMinimapButton then 
			RTC.PopupMinimap(self.button)
		else
			RTC.PopupMinimap(self)
		end
	end
end

function RTC.MenuToolTip(self)
	self:AddLine(RTC.Title)
	self:AddLine(L["MsgTooltip"])
end	

function RTC.ResizeButtons()
	local w = RollTrackerClassicFrameHelperButton:GetWidth()
	if RollTrackerClassicDB.NeedAndGreed then
		RollTrackerClassicFrameRollButton:SetWidth(w/3)
		RollTrackerClassicFramePassButton:SetWidth(w/3)
		RollTrackerClassicFrameGreedButton:Show()
	else
		RollTrackerClassicFrameRollButton:SetWidth(w/2)
		RollTrackerClassicFramePassButton:SetWidth(w/2)
		RollTrackerClassicFrameGreedButton:Hide()
	end
	
	if RollTrackerClassicDB.ShowNotRolled then
		RollTrackerClassicFrameAnnounceButton:SetWidth(w/3)
		RollTrackerClassicFrameClearButton:SetWidth(w/3)
		RollTrackerClassicFrameNotRolledButton:Show()
	else
		RollTrackerClassicFrameAnnounceButton:SetWidth(w/2)
		RollTrackerClassicFrameClearButton:SetWidth(w/2)
		RollTrackerClassicFrameNotRolledButton:Hide()
	end
	
end

function RTC.BtnClose()
	RTC.HideWindow()
	if RollTrackerClassicDB.ClearOnClose then
		RTC.ClearRolls()
	end
end

function RTC.BtnRoll()
	RandomRoll(1, 100)
end

function RTC.BtnGreed()
	RandomRoll(1, 50)
end

function RTC.BtnPass()
	RTC.AddChat("pass")
end

function RTC.BtnClearRolls()
	if #RTC.rollArray>0 then 
		RTC.ClearRolls()
		if RollTrackerClassicDB.CloseOnClear then
			RTC.HideWindow()
		end
	elseif #RTC.rollUndoArray>0 then
		RTC.UndoRolls()
	end
end

function RTC.BtnAnnounce()
	RTC.RollAnnounce()
	if RollTrackerClassicDB.ClearOnAnnounce then
		RTC.ClearRolls()
	end
	if RollTrackerClassicDB.CloseOnAnnounce then
		RTC.HideWindow()
	end
end

function RTC.BtnNotRolled()
	RTC.NotRolled()
end

function RTC.BtnSettings()
	if RTC.Tool.GetSelectedTab(RollTrackerClassicMainWindow)==1 then 
		RTC.Options:Open()
	else
		RTC.Options:Open(2)
	end
end

function RTC.BtnLootClear()
	if #RollTrackerClassicLoot>0 then
		RTC.ClearLoot()
	elseif #RTC.lootUndo>0 then
		RTC.UndoLoot()
	end
end

function RTC.SaveAnchors()
	RollTrackerClassicDB.X = RollTrackerClassicMainWindow:GetLeft()
	RollTrackerClassicDB.Y = RollTrackerClassicMainWindow:GetTop()
	RollTrackerClassicDB.Width = RollTrackerClassicMainWindow:GetWidth()
	RollTrackerClassicDB.Height = RollTrackerClassicMainWindow:GetHeight()
end

function RTC.ShowWindow(id)
	-- workaround for a strange bug
	if RollTrackerClassicMainWindow.Tabs then 
		for i=1, RollTrackerClassicMainWindow.numTabs do
			local child=RollTrackerClassicMainWindow.Tabs[i].content
			child:SetParent(RollTrackerClassicMainWindow)
			child:ClearAllPoints()
			child:SetPoint("TOPLEFT",8,-30)
			child:SetPoint("BOTTOMRIGHT",-8,8)			
		end
	end

	RollTrackerClassicMainWindow:Show()
	RTC.UpdateRollList()
	RTC.UpdateLootList()
	RTC.Tool.SelectTab(RollTrackerClassicMainWindow,id)
end

function RTC.HideWindow()
	RollTrackerClassicMainWindow:Hide()
end
	
-- Options Panel
function RTC.OptionsUpdate()
	RTC.LootListInit()
	RTC.CSVListInit()
	RTC.UpdateRollList()
	RTC.UpdateLootList()
	RTC.ResizeButtons()
	RTC.MinimapButton:UpdatePosition()
	
	local list=RTC.Tool.Split(RollTrackerClassicDB.LootTracker.WhiteList)
	RTC.whitelist={}
	for i,value in ipairs(list) do
		RTC.whitelist[value]=true
	end
	
	if RollTrackerClassicDB.LootTracker.Enable then
		RTC.Tool.TabShow(RollTrackerClassicMainWindow)
	else
		RTC.Tool.SelectTab(RollTrackerClassicMainWindow,1)
		RTC.Tool.TabHide(RollTrackerClassicMainWindow)		
	end
	
end

local function RTCO_CheckBox(Var,Init)
	RTC.Options:AddCheckBox(RollTrackerClassicDB,Var,Init,L["Cbox"..Var])
end
local function RTCO_CheckBoxLT(Var,Init)
	RTC.Options:AddCheckBox(RollTrackerClassicDB.LootTracker,Var,Init,L["CboxLT"..Var])
end

function RTC.OptionsInit()
	RTC.Options.Init(
		function()-- doOk
			RTC.Options:DoOk() 
			RTC.OptionsUpdate()
		end,
		function()-- doCancel
			RTC.Options:DoCancel() 
			RTC.OptionsUpdate()
		end,
		function()--doDefault
			RTC.Options:DoDefault() 
			RollTrackerClassicDB.Minimap.position=50
			RTC.ResetWindow()
			
			RTC.MinimapButton:UpdatePosition()
			
			RTC.OptionsUpdate()
		end
		)

	RTC.Options:SetScale(0.85)
	RTC.Options:AddPanel(L["RollTracker"])
	RTC.Options:AddVersion('|cff00c0ff' .. RTC.Version .. "|r")
	
	--RTC.Options:AddCategory( L["HeaderSettings"] ) 
	--RTC.Options:Indent()
	
	RTC.Options:AddCheckBox(RollTrackerClassicDB.Minimap,"visible",true,L["Cboxshowminimapbutton"])
	RTC.Options:AddCheckBox(RollTrackerClassicDB.Minimap,"lock",false,L["CboxLockMinimapButton"])
	RTC.Options:AddCheckBox(RollTrackerClassicDB.Minimap,"lockDistance",false,L["CboxLockMinimapButtonDistance"])
	RTC.Options:AddSpace()
	RTCO_CheckBox("ClearOnClose",true)	
	RTCO_CheckBox("ClearOnAnnounce", true)	
	RTCO_CheckBox("CloseOnAnnounce", true)	
	RTCO_CheckBox("CloseOnClear", true)
	RTC.Options:AddSpace()
	RTCO_CheckBox("IgnoreDouble", false)
	RTCO_CheckBox("RejectOutBounds", false)	
	RTCO_CheckBox("AnnounceIgnoreDouble", true)	
	RTCO_CheckBox("AnnounceRejectOutBounds",false)
	RTC.Options:AddSpace()
	RTCO_CheckBox("NeedAndGreed",false)
	RTCO_CheckBox("ShowNotRolled",true)
	RTC.Options:AddSpace()
	RTCO_CheckBox("ClearOnStart",false)
	RTCO_CheckBox("OpenOnStart",false)
	RTC.Options:AddSpace()
	RTCO_CheckBox("ColorName",true)
	RTCO_CheckBox("ShowClassIcon",true)
	RTC.Options:AddSpace()
	RTCO_CheckBox("AutoLootRolls",true)
	RTCO_CheckBox("AutoCloseLootRolls",true)
	RTC.Options:AddSpace()
	RTCO_CheckBox("OnDebug",false)
	
	
	-- loot tracker
	RTC.Options:AddPanel(L["PanelLootTracker"],false,true)
	
	RTC.Options:AddCategory( L["HeaderSettings"] ) 
	RTC.Options:Indent()
	RTCO_CheckBoxLT("Enable",false)
	RTC.Options:AddSpace()
	RTCO_CheckBoxLT("SmallFont",true)
	RTCO_CheckBoxLT("ShortMessage",false)
	RTCO_CheckBoxLT("ShowIcon",true)
	RTC.Options:AddSpace()
	RTCO_CheckBoxLT("TrackSolo",true)
	RTCO_CheckBoxLT("TrackGroup",true)
	RTCO_CheckBoxLT("TrackSRaid",true)
	RTCO_CheckBoxLT("TrackBRaid",true)
	RTC.Options:AddSpace()
	--lib:AddEditBox(DB,Var,Init,TXTLeft,width,widthLeft,onlynumbers,tooltip,suggestion)
	RTC.Options:AddEditBox(RollTrackerClassicDB.LootTracker,"NbLoots",1000,L["EdtNbLoots"],50,200,true)
	
	RTC.Options:AddEditBox(RollTrackerClassicDB.LootTracker,"WhiteList","",L["EdtWhiteList"],400,200)
	
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderRarity"])
	RTC.Options:Indent(10)
	for i=0,tonumber(RTC.MAXRARITY) do
		RTC.Options:AddCheckBox(RollTrackerClassicDB.LootTracker.Rarity,i,i>=2,
							ITEM_QUALITY_COLORS[i].hex .._G["ITEM_QUALITY"..i.."_DESC"].."|r")
	end
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderItemType"])
	RTC.Options:Indent()
	RTC.Options:AddText(L["TxtItemType"])
	for i = 0, NUM_LE_ITEM_CLASSS-1 do
		local txt=GetItemClassInfo(i)
		if txt~=nil and string.find(txt,"OBSOLETE")==nil then
			RTC.Options:AddCheckBox(RollTrackerClassicDB.LootTracker.ItemType,i,false,txt)
		end
	end
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderCSV"])
	RTC.Options:Indent(10)
	RTC.Options:AddText(L["TxtCSVJokersTitle"])
	RTC.Options:AddText(L["TxtCSVJokers"])
	RTC.Options:AddText(L["TxtCSVJokers2"])
	RTC.Options:AddSpace()
	--lib:AddEditBox(DB,Var,Init,TXTLeft,width,widthLeft,onlynumbers,tooltip,suggestion)
	RTC.Options:AddEditBox(RollTrackerClassicDB.LootTracker,
						"CSVexport",
						'%yy%-%mm%-%dd%;%HH%:%MM%;%name%;%iid%;%icount%',
						"",
						600)
	
	RTC.Options:Indent(-10)
	
	-- localization
	RTC.Options:SetScale(0.85)
	RTC.Options:AddPanel(L["HeaderCustomLocales"],false,true)
	RTC.Options:AddText(L["MsgLocalRestart"])
	RTC.Options:AddSpace()
	
	local locales=getmetatable(L).__index
	local t={}
	for key,value in pairs(locales) do 
		table.insert(t,key)
	end
	table.sort(t)
	for i,key in ipairs(t) do 
		local col=L[key]~=locales[key] and "|cffffffff" or "|cffff4040"
		local txt=L[key.."_org"]~="["..key.."_org]" and L[key.."_org"] or L[key]
		
		RTC.Options:AddEditBox(RollTrackerClassicDB.CustomLocales,key,"",col..L[key],450,200,false,locales[key],txt)

		
	end

	-- About
	local function SlashText(txt)
		RTC.Options:AddText(txt)
	end
	RTC.Options:AddPanel(L["PanelAbout"])

	RTC.Options:AddCategory("|cFFFF1C1C"..GetAddOnMetadata(TOCNAME, "Title") .." ".. GetAddOnMetadata(TOCNAME, "Version") .." by "..GetAddOnMetadata(TOCNAME, "Author"))
	RTC.Options:Indent(10)
	RTC.Options:AddText(GetAddOnMetadata(TOCNAME, "Notes"))		
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderInfo"])
	RTC.Options:Indent(10)
	RTC.Options:AddText(L["AboutInfo"],-20)
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderUsage"])
	RTC.Options:Indent(10)
	RTC.Options:AddText(L["AboutUsage"],-20)
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderSlashCommand"])
	RTC.Options:Indent(10)
	RTC.Options:AddText(L["AboutSlashCommand"],-20)
	RTC.Tool.PrintSlashCommand(nil,nil,SlashText)
	RTC.Options:Indent(-10)
	
	RTC.Options:AddCategory(L["HeaderCredits"])
	RTC.Options:Indent(10)
	RTC.Options:AddText(L["AboutCredits"],-20)
	RTC.Options:Indent(-10)
end

-- Init
function RTC.Init ()
	L=RTC.GetLocale()
	
	RTC.CSV_Transfer_Table={}

	RTC.rollArray = {}
	RTC.rollNames = {}
	RTC.rollUndoArray = {}
	RTC.rollUndoNames = {}
	RTC.lootUndo={}
	
	RTC.LootHistoryCloseTimer=0	
	RTC.LootHistoryCountHandle=0
	RTC.LootHistoryHandle={}
	RTC.LootHistoryCleardRollID={}
	
	-- using strings from GlobalStrings.lua
	RTC.PatternRoll = RTC.Tool.CreatePattern(RANDOM_ROLL_RESULT)
	RTC.PatternLoot = RTC.Tool.CreatePattern(LOOT_ITEM,true)
	RTC.PatternLootOwn = RTC.Tool.CreatePattern(LOOT_ITEM_SELF,true)
	RTC.PatternCreateOwn = RTC.Tool.CreatePattern(LOOT_ITEM_CREATED_SELF ,true)
	
	-- settings
	if not RollTrackerClassicDB then RollTrackerClassicDB = {} end -- fresh DB	
	if not RollTrackerClassicDB.Minimap then RollTrackerClassicDB.Minimap = {} end 
	if not RollTrackerClassicDB.CustomLocales then RollTrackerClassicDB.CustomLocales = {} end 
	if not RollTrackerClassicLoot then RollTrackerClassicLoot = {} end
	if not RollTrackerClassicDB.LootTracker then RollTrackerClassicDB.LootTracker  = {} end
	if not RollTrackerClassicDB.LootTracker.Rarity then RollTrackerClassicDB.LootTracker.Rarity  = {} end
	if not RollTrackerClassicDB.LootTracker.ItemType then RollTrackerClassicDB.LootTracker.ItemType  = {} end
	
	local x, y, w, h = RollTrackerClassicDB.X, RollTrackerClassicDB.Y, RollTrackerClassicDB.Width, RollTrackerClassicDB.Height
	if not x or not y or not w or not h then
		RTC.SaveAnchors()
	else
		RollTrackerClassicMainWindow:ClearAllPoints()
		RollTrackerClassicMainWindow:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x, y)
		RollTrackerClassicMainWindow:SetWidth(w)
		RollTrackerClassicMainWindow:SetHeight(h)
	end
	
	-- Language
	RollTrackerClassicMainWindowTitle:SetText(string.format(RTC.TxtEscapePicture,RTC.IconDice).. RTC.Title)
	
	RollTrackerClassicFrameRollButton:SetText(string.format(RTC.TxtEscapePicture,RTC.IconDice).. L["BtnRoll"])
	RollTrackerClassicFrameGreedButton:SetText(string.format(RTC.TxtEscapePicture,RTC.IconGreed)..L["BtnGreed"])
	RollTrackerClassicFramePassButton:SetText(string.format(RTC.TxtEscapePicture,RTC.IconPass)..L["BtnPass"])
	
	--RollTrackerClassicFrameClearButton:SetText(L["BtnClear"])	
	RollTrackerClassicFrameAnnounceButton:SetText(L["BtnAnnounce"])
	RollTrackerClassicFrameNotRolledButton:SetText(L["BtnNotRolled"])
	RollTrackerClassicFrameHelperButton:Hide()
	RTC.ResizeButtons()
	
	RollTrackerClassicLootFrameClearButton:SetText(L["BtnClear"])	
	
	RollTrackerClassicCSVFrameExportButton:SetText(L["BtnCSVExport"])
	
	
	-- slash command
	local function doDBSet(DB,var,value)
		if value==nil then
			DB[var]= not DB[var]
		elseif tContains({"true","1","enable"},value) then
			DB[var]=true
		elseif tContains({"false","0","disable"},value) then
			DB[var]=false
		end
		DEFAULT_CHAT_FRAME:AddMessage(RTC.MSGPREFIX.."Set "..var.." to "..tostring(DB[var]))
		RTC.OptionsUpdate()
	end
	
	RTC.Tool.SlashCommand({"/rtc","/rt","/rolltracker","/rolltrackerclassic"},{
		{"clear","",{
				{"rolls",L["SlashClearRolls"],RTC.ClearRolls,true},
				{"loot",L["SlashClearLoot"],RTC.ClearLoot,true},
				{"lootrolls",L["SlashClearLootRolls"],RTC.LootHistoryClear},
			},
		},
		{"undo","",{
				{"rolls",L["SlashUndoRolls"],RTC.UndoRolls,true},
				{"loot",L["SlashUndoLoot"],RTC.UndoLoot,true},
			},
		},
		{"announce",L["SlashAnnounce"],RTC.RollAnnounce},
		{"notrolled",L["SlashNotRolled"],RTC.NotRolled},
		{"close",L["SlashClose"],RTC.HideWindow},
		{"reset",L["SlashReset"],RTC.ResetWindow},
		{{"config","setup","options"},L["SlashConfig"],RTC.Options.Open,RTC.Options,1},
		{"about",L["SlashAbout"],RTC.Options.Open,RTC.Options,4},
		{"debug","",{
				{"%","",RTC.AddRoll}
			},
		},
		{"start","",{
				{"%",L["SlashStart"],RTC.StartRoll}
			},
		},
		{"loottracker","",{
				{"%",L["CboxLTEnable"],doDBSet,RollTrackerClassicDB.LootTracker,"Enable"}
			},
		},
		{"export",L["BtnCSVExport"],RTC.BtnExport},
		{"raidroll","",{
				{"list",L["SlashRaidRollList"],RTC.RaidRollList},
				{"",L["SlashRaidRoll"],RTC.RaidRoll},
			},
		},
		{"",L["SlashOpen"],RTC.ShowWindow},
	})


	-- Options
	RTC.OptionsInit()
	
	--gui
	RTC.MinimapButton.Init(RollTrackerClassicDB.Minimap,RTC.IconDice,RTC.MenuButtonClick,RTC.Title.."\n"..L["MsgTooltip"])	
	
	RTC.Tool.EnableSize(RollTrackerClassicMainWindow,8,nil,function() RTC.SaveAnchors()	end)
	
	RTC.Tool.AddTab(RollTrackerClassicMainWindow,L["TabRoll"],RollTrackerClassicFrame)
	RTC.Tool.AddTab(RollTrackerClassicMainWindow,L["TabLoot"],RollTrackerClassicLootFrame)
	RTC.Tool.AddTab(RollTrackerClassicMainWindow,L["TabCSV"],RollTrackerClassicCSVFrame)
	
	RTC.PopupDynamic=RTC.Tool.CreatePopup(RTC.OptionsUpdate)
		
	-- timer
	local FakeTimer=CreateFrame("Frame")
	FakeTimer:SetScript("OnUpdate",
		function()
			if RTC.LootHistoryCloseTimer>0 and RTC.LootHistoryCloseTimer<time() and RTC.LootHistoryCountHandle<=0 then
				if RollTrackerClassicDB.AutoCloseLootRolls then
					LootHistoryFrame_CollapseAll(LootHistoryFrame)
					LootHistoryFrame:Hide()
				end
				RTC.LootHistoryCloseTimer=0
				RTC.LootHistoryCountHandle=0
			end
		end
		)
		
	RTC.OptionsUpdate()
end

-- Event handler
function RTC.OnEvent(event, ...)	
	local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg, arg9 = ...
	--print("rtc-event:"..event.." "..arg1)
	if  event == "ADDON_LOADED" then
		if arg1 == TOCNAME then
			RTC.Init()
		end
		RTC.Tool.AddDataBrocker(RTC.IconDice, RTC.MenuButtonClick, RTC.MenuToolTip)
		
	elseif event=="START_LOOT_ROLL" then
		--START_LOOT_ROLL: rollID, rollTime, lootHandle
		if RollTrackerClassicDB.AutoLootRolls then
			RTC.LootHistoryShow(arg1)
		end
		RTC.LootHistoryHandle[arg3]=true
		RTC.LootHistoryCountHandle=RTC.LootHistoryCountHandle+1
		RTC.LootHistoryCloseTimer=0	
		
	elseif event=="LOOT_ROLLS_COMPLETE" then
		--LOOT_ROLLS_COMPLETE: lootHandle
		if RTC.LootHistoryHandle[arg1]==true then
			RTC.LootHistoryHandle[arg1]=nil
			RTC.LootHistoryCountHandle=RTC.LootHistoryCountHandle-1
			if RTC.LootHistoryCountHandle==0 then
				RTC.LootHistoryCloseTimer=time()+RTC.LootHistoryCloseTimerTIME				
			end	
		end

	elseif event == "CHAT_MSG_LOOT"  then
		RTC.CHAT_MSG_LOOT(arg1)
	
	elseif event == "CHAT_MSG_SYSTEM" then
		RTC.CHAT_MSG_SYSTEM(arg1)
		
	elseif (event == "CHAT_MSG_PARTY" or event == "CHAT_MSG_PARTY_LEADER" or event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER") then
		RTC.CHAT_MSG_GROUP(arg1,arg2)
	end
end

function RTC.OnLoad()
    --print("rtc-onload")
	RollTrackerClassicMainWindow:SetMinResize(194,170)
	RollTrackerClassicMainWindow:RegisterForDrag("LeftButton")
	RollTrackerClassicMainWindow:RegisterEvent("ADDON_LOADED")
	RollTrackerClassicMainWindow:RegisterEvent("CHAT_MSG_SYSTEM")
	RollTrackerClassicMainWindow:RegisterEvent("CHAT_MSG_PARTY")
	RollTrackerClassicMainWindow:RegisterEvent("CHAT_MSG_PARTY_LEADER")
	RollTrackerClassicMainWindow:RegisterEvent("CHAT_MSG_RAID")
	RollTrackerClassicMainWindow:RegisterEvent("CHAT_MSG_RAID_LEADER")
	RollTrackerClassicMainWindow:RegisterEvent("START_LOOT_ROLL")
	RollTrackerClassicMainWindow:RegisterEvent("LOOT_ROLLS_COMPLETE")
	RollTrackerClassicMainWindow:RegisterEvent("CHAT_MSG_LOOT")
end

function RTC.OnDragStart()
	RollTrackerClassicMainWindow:StartMoving()
end

function RTC.OnDragStop()
	RollTrackerClassicMainWindow:StopMovingOrSizing();
	RTC.SaveAnchors()
end

function RTC.CHAT_MSG_LOOT (arg1)
	
	-- %s receives loot : %s|Hitem :%d :%d :%d :%d|h[%s]|h%s. 
	name, item =string.match(arg1, RTC.PatternLoot)
	if not name or not item then
		name=GetUnitName("player")
		item=string.match(arg1, RTC.PatternLootOwn)
	end
	
	if name~=nil and item~=nil then
		RTC.AddLoot(name,item)
	end	
	
	-- You create : %s|Hitem :%d :%d :%d :%d|h[%s]|h%s. 
	--for item,b,c,d in string.gmatch(arg1, RTC.PatternCreateOwn) do
	--	RTC.AddLoot(GetUnitName("player"),item)
	--end
end

function RTC.CHAT_MSG_SYSTEM (arg1)
	for name, roll, low, high in string.gmatch(arg1, RTC.PatternRoll) do
		--print(".."..name.." "..roll.." "..low.." "..high)		
		RTC.AddRoll(name,roll,low,high)		
	end
	
end

function RTC.CHAT_MSG_GROUP (msg,name)
	if msg == L["pass"] or msg == "pass" then
		name=RTC.Tool.Split(name, "-")[1]
		RTC.AddRoll(name,"0","1","100")
	end	
	
	if string.sub(msg,1,string.len(RTC.MSGPREFIX_START))==RTC.MSGPREFIX_START then
		if RollTrackerClassicDB.ClearOnStart then 
			RTC.ClearRolls()
		end
		if RollTrackerClassicDB.OpenOnStart then 
			RTC.ShowWindow(1)
		end
	end
	
	
end

-- Roll 

function RTC.RaidRoll()
	RTC.IsRaidRoll=RTC.GetPlayerList(true)
	RandomRoll(1, #RTC.IsRaidRoll)
end

function RTC.RaidRollList()
	local party=RTC.GetPlayerList(true)
	for i,entry in ipairs(party) do
		RTC.AddChat(i..". "..entry.name)
	end
end


function RTC.AddRoll(name,roll,low,high)
	local ok=false
	if RTC.IsRaidRoll and low=="1" and tonumber(high)==#RTC.IsRaidRoll and name==GetUnitName("player") then
		roll=tonumber(roll)
		RTC.AddChat(RTC.MSGPREFIX..string.format(L["MsgRaidRoll"],RTC.IsRaidRoll[roll].name,roll))
		RTC.IsRaidRoll=nil
		return 
	end
	
	
	-- check for rerolls. >1 if rolled before
	if RollTrackerClassicDB.NeedAndGreed then
		if (RollTrackerClassicDB.IgnoreDouble==false or RTC.rollNames[name]==nil or RTC.rollNames[name]==0) and
		   ((low=="1" and high=="50") or (low=="1" and high=="100")) then
			ok=true
		end
	else
		if (RollTrackerClassicDB.IgnoreDouble==false or RTC.rollNames[name]==nil or RTC.rollNames[name]==0) and
		   (RollTrackerClassicDB.RejectOutBounds==false or (low=="1" and high=="100")) then
			ok=true
		end
	end
	
	if ok then
		RTC.rollNames[name] = RTC.rollNames[name] and RTC.rollNames[name] + 1 or 1
		table.insert(RTC.rollArray, {
			Name = name,
			Roll = tonumber(roll),
			Low = tonumber(low),
			High = tonumber(high),
			Count = RTC.rollNames[name]
		})
		
		RTC.ShowWindow(1)
		
	else	
		DEFAULT_CHAT_FRAME:AddMessage(string.format(RTC.MSGPREFIX .. L["MsgCheat"],name,roll,low,high))
	end
end

function RTC.SortRolls(a, b)
	return a.Roll < b.Roll
end

function RTC.FormatRollText (roll,party,partyName)
	local colorTied= "|cffffffff"
	local colorCheat=((roll.Low ~= 1 or roll.High ~= 100) or (roll.Count > 1)) and  "|cffffcccc" or "|cffffffff"
	local txtRange=(roll.Low ~= 1 or roll.High ~= 100) and format(" (%d-%d)", roll.Low, roll.High)  or ""
	
	local colorName
	local iconClass
	
	if partyName[roll.Name] and partyName[roll.Name].class then
		colorName="|c"..RAID_CLASS_COLORS[partyName[roll.Name].class].colorStr
		iconClass=RTC.Tool.IconClass[partyName[roll.Name].class]
	end
	if colorName==nil or RollTrackerClassicDB.ColorName==false then colorName=colorCheat end
	if iconClass==nil or RollTrackerClassicDB.ShowClassIcon==false then iconClass=""	end
	
	local txtCount=roll.Count > 1 and format(" [%d]", roll.Count) or ""
	
	return colorTied..string.format("%3d",roll.Roll).."|r: "..
			iconClass..colorName.. roll.Name.."|r "..
			colorCheat..txtRange.."|r "..
			colorCheat..txtCount.."\n"

end

function RTC.UpdateRollList ()
	local rollText = ""
	
	local party,partyName = RTC.GetPlayerList()
	
	table.sort(RTC.rollArray, RTC.SortRolls)
	
	-- format and print rolls, check for ties
	if RollTrackerClassicDB.NeedAndGreed then
		local rtxt=""
		for i, roll in pairs(RTC.rollArray) do
			if roll.Roll>0 and roll.High == 100 then
				rtxt=RTC.FormatRollText(roll,party,partyName)..rtxt
			end
		end
		rollText = "|cFFAAAAAA" .. L["TxtNeed"] .."\n" .. rtxt 		
		rtxt=""
		for i, roll in pairs(RTC.rollArray) do
			if roll.Roll==0 or roll.High == 50 then
				rtxt=RTC.FormatRollText(roll,party,partyName)..rtxt
			end			
		end
		rollText = rollText .. "\n|cFFAAAAAA" .. L["TxtGreed"] .. "\n" .. rtxt
	else
		for i, roll in pairs(RTC.rollArray) do
			rollText=RTC.FormatRollText(roll,party,partyName) .. rollText
		end
	end

	--if IsInGroup() or IsInRaid() then
	rollText = rollText.."|cFFAAAAAA" .. L["TxtLine"] .. "\n"
	local gtxt=""
	local missClasses={}
	for i,p in ipairs(party) do 
		if RTC.rollNames[p.name]==nil or RTC.rollNames[p.name]==0 then
			local iconClass=RTC.Tool.IconClass[partyName[p.name].class]
			if iconClass==nil or RollTrackerClassicDB.ShowClassIcon==false then 
				iconClass=""	
			else
				missClasses[partyName[p.name].class]=missClasses[partyName[p.name].class] and missClasses[partyName[p.name].class]+1 or 1
			end
			gtxt = gtxt.. iconClass .. p.name .."\n"
		end
	end
	local ctxt=""
	if IsInRaid() then 
		local isHorde=(UnitFactionGroup("player"))=="Horde"
		for i,class in pairs (RTC.Tool.Classes) do
		--for class,count in pairs(missClasses) do
			if not(isHorde and class=="PALADIN") and not(not isHorde and class=="SHAMAN") then 
				ctxt=ctxt..RTC.Tool.IconClass[class]..(missClasses[class] or 0).." "
			end
		end
		if ctxt~="" then ctxt=ctxt.."\n" .. L["TxtLine"] .. "\n" end
	end
	
	rollText=rollText..ctxt..gtxt

	
	--end
	
	RollTrackerRollText:SetText(rollText)
	RollTrackerClassicFrameStatusText:SetText(string.format(L["MsgNbRolls"], table.getn(RTC.rollArray)))

	if #RTC.rollArray==0 and #RTC.rollUndoArray>0 then
		RollTrackerClassicFrameClearButton:SetText(L["BtnUndo"])
	else
		RollTrackerClassicFrameClearButton:SetText(L["BtnClear"])	
	end
	
end

function RTC.ClearRolls (doMsg)
	if #RTC.rollArray>0 then
		if doMsg then
			DEFAULT_CHAT_FRAME:AddMessage(RTC.MSGPREFIX .. L["MsgRollCleared"])
		end
	
		RTC.rollUndoArray = RTC.rollArray
		RTC.rollUndoNames = RTC.rollNames
		RTC.rollArray = {}
		RTC.rollNames = {}			
	end
	RTC.UpdateRollList()
end

function RTC.UndoRolls (doMsg)
	if #RTC.rollUndoArray>0 then
		if doMsg then
			DEFAULT_CHAT_FRAME:AddMessage(RTC.MSGPREFIX .. L["MsgUndoRoll"])
		end
		RTC.rollArray = RTC.rollUndoArray
		RTC.rollNames = RTC.rollUndoNames
		RTC.rollUndoArray = {}
		RTC.rollUndoNames = {}	
		RTC.UpdateRollList()
	end
end

function RTC.NotRolled ()
	if IsInGroup() or IsInRaid() then
	
		local party,partyName = RTC.GetPlayerList()
		local names=""
		for i,p in ipairs(party) do 
			if RTC.rollNames[p.name]==nil or RTC.rollNames[p.name]==0 then
				names = names ..", ".. p.name
			end
		end
		names=string.sub(names,3)
		
		if names ~= "" then 
			RTC.AddChat(RTC.MSGPREFIX .. string.format(L["MsgNotRolled"] ,L["pass"]))
			RTC.AddChat(names)							
		end
		
	end
end

function RTC.StartRoll (...)
	local msg
	local item=RTC.Tool.Combine({...})
	RTC.ShowWindow(1)
	RTC.ClearRolls()
	if RollTrackerClassicDB.NeedAndGreed then
		msg=L["MsgStartGreenAndNeed"]
	else
		msg=L["MsgStart"]
	end
	RTC.AddChat(RTC.MSGPREFIX_START .. string.format(msg,L["pass"]))
	if item and item~="" and item~=" " then
		RTC.AddChat(RTC.MSGPREFIX .. string.format(L["MsgNextItem"],item))
	end
	RTC.AddChat(L["MsgBar"])
end	

function RTC.RollAnnounce ()
	local winNum=0
	local winName=""
	local max=-1
	local addPrefix=""
	local msg=""
	if RollTrackerClassicDB.NeedAndGreed then
		for i, roll in pairs(RTC.rollArray) do		
			if (RollTrackerClassicDB.AnnounceIgnoreDouble==false or roll.Count==1) and
			  (roll.Roll>0 and roll.Low==1 and roll.High==100) then
		
				if roll.Roll==max then
					winNum=winNum+1
					winName=winName..", "..roll.Name
				elseif roll.Roll>max then
					max=roll.Roll
					winNum=1
					winName=roll.Name
				end
			end
		end
		
		if winNum==0 then
			for i, roll in pairs(RTC.rollArray) do		
				if (RollTrackerClassicDB.AnnounceIgnoreDouble==false or roll.Count==1) and
				  (roll.Roll == 0 or ( roll.Low==1 and roll.High==50)) then
			
					if roll.Roll==max then
						winNum=winNum+1
						winName=winName..", "..roll.Name
					elseif roll.Roll>max then
						max=roll.Roll
						winNum=1
						winName=roll.Name
					end
				end
			end
			addPrefix=L["TxtGreed"].."! "
		else
			addPrefix=L["TxtNeed"].."! "
		end
		
	else
		for i, roll in pairs(RTC.rollArray) do
		
			if (RollTrackerClassicDB.AnnounceIgnoreDouble==false or roll.Count==1) and
			  (RollTrackerClassicDB.AnnounceRejectOutBounds==false or (roll.Low==1 and roll.High==100)) then
		
				if roll.Roll==max then
					winNum=winNum+1
					winName=winName..", "..roll.Name
				elseif roll.Roll>max then
					max=roll.Roll
					winNum=1
					winName=roll.Name
				end
			end
		end
	end
	
	if winNum==1 then 
		msg=RTC.MSGPREFIX .. addPrefix .. string.format(L["MsgAnnounce"] ,winName,max) 
	elseif winNum>1 then
		msg=RTC.MSGPREFIX .. addPrefix .. string.format(L["MsgAnnounceTie"] ,winName,max) 
	end
	
	RTC.AddChat(msg)

end

-- Loot

function RTC.AddLoot (name,lootitem)
	if name==nil or lootitem==nil or not RollTrackerClassicDB.LootTracker.Enable then return end
	
	local ok=false
	if IsInRaid() then
		local count=GetNumGroupMembers()
		if RollTrackerClassicDB.LootTracker.TrackSRaid and count<=10 then
			ok=true
		elseif RollTrackerClassicDB.LootTracker.TrackBRaid and count>=11 then
			ok=true
		end
	elseif IsInGroup() then
		if RollTrackerClassicDB.LootTracker.TrackGroup then
			ok=true
		end
	elseif RollTrackerClassicDB.LootTracker.TrackSolo then
		ok=true
	end
	
	if not ok then return end
	
	local _,PartyNames = RTC.GetPlayerList()
	local t=time()
	local class
	if PartyNames[name] then
		class=PartyNames[name].class
	end
	
	local loot={
		["name"]=name,
		["class"]=class,
		["timestamp"]=t,
		}
	RollTrackerClassicDB.DEBUGHELP_ITEM=lootitem
	
	loot.itemName, loot.itemLink, loot.itemRarity, loot.itemLevel, _, _,
		_, _, _, loot.itemIcon, loot.itemSellPrice,loot.itemType =GetItemInfo(string.match(lootitem,"|H(.+)%["))
	
	loot.ItemCount=tonumber(string.match(lootitem,"|rx(%d+)") or 1)

	
	if RollTrackerClassicDB.LootTracker.Rarity[loot.itemRarity] or 
			RollTrackerClassicDB.LootTracker.ItemType[loot.itemType] or
				RTC.whitelist[string.match(loot.itemLink,"item:(.-):") or 0] then
		
		while #RollTrackerClassicLoot>=RollTrackerClassicDB.LootTracker.NbLoots do
			tremove(RollTrackerClassicLoot,1)
		end
		
		tinsert(RollTrackerClassicLoot,loot)	
		RTC.CSVList_AddItem(loot)
		RTC.LootList_AddItem(loot)
		RTC.UpdateLootList()		
	end
	
	
	
	
end

function RTC.ClearLoot(doMsg)
	if #RollTrackerClassicLoot>0 then
		if doMsg then
			DEFAULT_CHAT_FRAME:AddMessage(RTC.MSGPREFIX .. L["MsgLootCleared"])
		end
		RTC.lootUndo = RollTrackerClassicLoot
		RollTrackerClassicLoot={}
		RTC.OptionsUpdate()
	end
end

function RTC.UndoLoot (doMsg)
	if #RTC.lootUndo>0 then
		if doMsg then
			DEFAULT_CHAT_FRAME:AddMessage(RTC.MSGPREFIX .. L["MsgUndoLoot"])
		end
		RollTrackerClassicLoot = RTC.lootUndo
		RTC.lootUndo = {}	
		RTC.OptionsUpdate()
	end
end

function RTC.LootList_AddItem (loot)
	local colorName
	local iconClass
	local icon
	if not loot.itemIcon or not RollTrackerClassicDB.LootTracker.ShowIcon then
		icon=""
	else
		icon=string.format(RTC.TxtEscapeIcon,loot.itemIcon)
	end
	
	if loot.class then
		colorName="|c"..RAID_CLASS_COLORS[loot.class].colorStr
		iconClass=RTC.Tool.IconClass[loot.class]
	end
	if colorName==nil or RollTrackerClassicDB.ColorName==false then colorName="" end
	if iconClass==nil or RollTrackerClassicDB.ShowClassIcon==false then iconClass="" end
	
	local stack
	if loot.ItemCount~=nil and loot.ItemCount>1 then
		stack="x"..loot.ItemCount
	else
		stack=""
	end	
	
	local Text
	if RollTrackerClassicDB.LootTracker.ShortMessage then
		Text=iconClass..colorName.. loot.name.."|r".." "..icon..loot.itemLink..stack
	else
		Text=string.format(L["MsgLootLine"],
					date("%y-%m-%d %H:%M",loot.timestamp),
					iconClass..colorName.. loot.name.."|r",
					icon..loot.itemLink..stack
					)
	end
	RollTrackerClassicLootFrame_MessageFrame:AddMessage( Text,.8,.8,.8)
end

function RTC.LootListInit()

	RollTrackerClassicLootFrame_MessageFrame:SetFading(false);
	if RollTrackerClassicDB.LootTracker.SmallFont then
		RollTrackerClassicLootFrame_MessageFrame:SetFontObject(GameFontNormalSmall);
	else
		RollTrackerClassicLootFrame_MessageFrame:SetFontObject(GameFontNormal);
	end
	RollTrackerClassicLootFrame_MessageFrame:SetJustifyH("LEFT");
	RollTrackerClassicLootFrame_MessageFrame:SetHyperlinksEnabled(true);
	RollTrackerClassicLootFrame_MessageFrame:SetTextCopyable(true);
	RollTrackerClassicLootFrame_MessageFrame:Clear()
	RollTrackerClassicLootFrame_MessageFrame:SetMaxLines(RollTrackerClassicDB.LootTracker.NbLoots)

	if RollTrackerClassicDB.LootTracker.Enable then 
		for i,loot in ipairs(RollTrackerClassicLoot) do
			RTC.LootList_AddItem(loot)
		end
	else
		RollTrackerClassicLootFrame_MessageFrame:AddMessage( L["MsgLTnotenabled"],.8,.8,.8)
	end

end

function RTC.UpdateLootList()

	if RollTrackerClassicDB.LootTracker.Enable then 
		RollTrackerClassicLootFrameStatusText:SetText(string.format(L["MsgNbLoots"],#RollTrackerClassicLoot))
	else
		RollTrackerClassicLootFrameStatusText:SetText("")
	end
	
	if #RollTrackerClassicLoot==0 and #RTC.lootUndo>0 then
		RollTrackerClassicLootFrameClearButton:SetText(L["BtnUndo"])
	else
		RollTrackerClassicLootFrameClearButton:SetText(L["BtnClear"])	
	end	
end
	
function RTC.ScrollLootList(self,delta)
	self:SetScrollOffset(self:GetScrollOffset() + delta*5);
	self:ResetAllFadeTimes()
end
function RTC.ScrollCSVList(self,delta)
	self:SetScrollOffset(self:GetScrollOffset() + delta*5);
	self:ResetAllFadeTimes()
end

function RTC.CSVList_AddItem (loot,hide)

	RTC.CSV_Transfer_Table["%%"]="%"
	RTC.CSV_Transfer_Table["%name%"]=loot.name
	RTC.CSV_Transfer_Table["%class%"]=loot.class
	RTC.CSV_Transfer_Table["%timestamp%"]=loot.timestamp
	RTC.CSV_Transfer_Table["%dd%"]=date("%d",loot.timestamp)
	RTC.CSV_Transfer_Table["%mm%"]=date("%m",loot.timestamp)
	RTC.CSV_Transfer_Table["%yy%"]=date("%y",loot.timestamp)
	RTC.CSV_Transfer_Table["%HH%"]=date("%H",loot.timestamp)
	RTC.CSV_Transfer_Table["%MM%"]=date("%M",loot.timestamp)
	RTC.CSV_Transfer_Table["%SS%"]=date("%S",loot.timestamp)
	RTC.CSV_Transfer_Table["%iname%"]=loot.itemName
	RTC.CSV_Transfer_Table["%irarity%"]=loot.itemRarity
	RTC.CSV_Transfer_Table["%iraritytxt%"]=_G["ITEM_QUALITY".. loot.itemRarity .."_DESC"]
	RTC.CSV_Transfer_Table["%ilevel%"]=loot.itemLevel
	RTC.CSV_Transfer_Table["%iid%"]=string.match(loot.itemLink,"item:(.-):")
	RTC.CSV_Transfer_Table["%iprice%"]=loot.itemSellPrice
	RTC.CSV_Transfer_Table["%icount%"]=loot.ItemCount or 1
	RTC.CSV_Transfer_Table["%itype%"]=loot.itemType or 99
	RTC.CSV_Transfer_Table["%itypetxt%"]=GetItemClassInfo(loot.itemType or 99) or ""
		
	
	local text= string.gsub(RollTrackerClassicDB.LootTracker.CSVexport,"%%%w-%%",RTC.CSV_Transfer_Table)	
	
	if hide then
		return text
	else
		RollTrackerClassicCSVFrame_MessageFrame:AddMessage( text,.8,.8,.8)
	end
end

function RTC.CSVListInit()

	RollTrackerClassicCSVFrame_MessageFrame:SetFading(false);
	RollTrackerClassicCSVFrame_MessageFrame:SetFontObject(GameFontNormalSmall);
	RollTrackerClassicCSVFrame_MessageFrame:SetJustifyH("LEFT");
	RollTrackerClassicCSVFrame_MessageFrame:SetHyperlinksEnabled(true);
	RollTrackerClassicCSVFrame_MessageFrame:SetTextCopyable(true);
	RollTrackerClassicCSVFrame_MessageFrame:Clear()
	RollTrackerClassicCSVFrame_MessageFrame:SetMaxLines(RollTrackerClassicDB.LootTracker.NbLoots)
	
	for i,loot in ipairs(RollTrackerClassicLoot) do
		RTC.CSVList_AddItem(loot)
	end

end

function RTC.BtnExport()
	local Text=""
	for i,loot in ipairs(RollTrackerClassicLoot) do
		Text=Text..RTC.CSVList_AddItem(loot,true).."\n"
	end
	RTC.Tool.CopyPast(Text)
end
	