----------------------------------------
--Chat.lua
--handles the chat-channels functions
----------------------------------------


local L = LibStub("AceLocale-3.0"):GetLocale("BossTactics")
local BabbleClass = LibStub("LibBabble-Class-3.0"):GetLookupTable();


function BossTactics:SendMessageToChannel(info, msg)

	if(not  UnitInRaid(self.player)) then
		self:Print(L["you are not in a raid"])
		return
	end
	--info[1] is the channel name
    if(strlen(msg) == 0)then return end
	local message = ""
	local channelinfo = self:GetChannelInfoFromShortcut(info[1])

    if(channelinfo == nil)then
		self:Print(format(L["channel not found"],info[1]))
	else
	    if(self:CheckInChannel(channelinfo.id))then
            message = "{CH:"..channelinfo.id..":"..self:EncodeItemLink(msg).."}"
            self:BT_SendDataMessage(message)
        else
            self:Print(L["you are not in this channel"])
        end
    end
end;

--------------------------------------
--shows the current members of a channel
--------------------------------------
function BossTactics:ChatInfo(info, name)

	if(not  UnitInRaid(self.player)) then
		self:Print(L["you are not in a raid"])
		return
	end
	local channelinfo = self:GetChannelInfoFromShortcut(name)
	if(channelinfo == nil)then
		self:Print(format(L["channel not found"],name))
	else
	    if(self:CheckInChannel(channelinfo.id))then
            message = "{CHW:"..channelinfo.id.."}"
            self:Print(format (L["members of channel"],channelinfo.name))
            self:BT_SendDataMessage(message)

        else
            self:Print(L["you are not in this channel"])
        end
    end
end;

-----------------------------------------
--shows the current joined channels
-----------------------------------------
function BossTactics:ChannelInfo()

	local tbl = {}
	for i,v in ipairs (self.db.char.joinedChannelList)do
		local channelInfo = self:GetChannelInfoFromId(v)
		tinsert(tbl,channelInfo.name)
	end
	table.sort(tbl)
	local out = table.concat(tbl, ", ")
	self:Print(format (L["you are in channels: "],out))
end;

----------------------------------------------------
--handles chatmessages
----------------------------------------------------

function BossTactics:CheckChat(msgs,distribution,target)

	local regex_channel = "{CH:([^:]-):([^}]-)}"
	local regex_channelWho = "{CHW:([^}]-)}"
	local regex_channelAnswer = "{CHME}"

	local msg = self:DecodeItemLink(msgs)
    for chid, message in string.gmatch(msg,regex_channel) do
        local channelInfo = self:GetChannelInfoFromId(tonumber(chid))
        if(self:CheckInChannel(channelInfo.id)) then
            message = string.gsub(message,"|r","|r|cff"..channelInfo.color)
            message = "|cff"..channelInfo.color.."[BT:"..channelInfo.name.."]["..target.."]: "..message.."|r"
        	DEFAULT_CHAT_FRAME:AddMessage(message,1,1,1)
        end
    end

    for chid in string.gmatch(msgs,regex_channelWho) do
    	if(self:CheckInChannel(tonumber(chid))) then
    		self:BT_SendDataMessage("{CHME}",true,target)
    	end
    end

    if(msgs == regex_channelAnswer)then
    	self:Print(target)
    end

end;


function BossTactics:CheckInChannel(id)

	for i,v in ipairs(self.db.char.joinedChannelList)do
		if(v == id)then
			return true
		end
	end
	return false

end;

function BossTactics:HandleBinding(chan)

	local channinfo = self:GetChannelInfoFromId(tonumber(chan))
	if ( not ChatFrameEditBox:IsVisible() ) then
		ChatFrame_OpenChat("/bt "..channinfo.shortcuts[1].." ");
	else
		ChatFrameEditBox:SetText("/bt "..channinfo.shortcuts[1].." ");
	end

end

--------------------------------------------------
--handles to join a channel
-------------------------------------------------

function BossTactics:JoinChannel(join, args)

	local channinfo = self:GetChannelInfoFromShortcut(args)
	if(channinfo == nil)then
		self:Print(format(L["channel not found"],args))
	else
		if(self:CheckInChannel(channinfo.id))then
			self:Print(format(L["already in channel"],channinfo.name))
		else
			tinsert(self.db.char.joinedChannelList,channinfo.id)
			self:Print(format(L["channel joined"],channinfo.color,channinfo.name))
		end
	end
end;

--------------------------------------------------
--handles to quit a channel
-------------------------------------------------

function BossTactics:QuitChannel(quit, args)

	local channinfo = self:GetChannelInfoFromShortcut(args)
	if(channinfo == nil)then
		self:Print(format(L["channel not found"],args))
	else
		if(self:CheckInChannel(channinfo.id))then
			for i,v in ipairs(self.db.char.joinedChannelList,channinfo.id)do
				if(v == channinfo.id)then
					tremove(self.db.char.joinedChannelList,i)
					break
				end
			end
			self:Print(format(L["channel quit"],channinfo.color,channinfo.name))
		else

		end
	end
end;

---------------------------------------------------
--config the chat
---------------------------------------------------


function BossTactics:ChatConfig()
	self:ShowChatConfigFrame()
end;


function BossTactics:UpdateColor(r,g,b)
	local hexcode = self:RgbToHex(r,g,b)
	local selChan = self.ChatConfigFrame.ChannelBtn:GetText()
	--change the value in the memory
	local chaninfo = self:GetChannelInfoFromShortcut(selChan)
	chaninfo.color = hexcode
	--change the text field
	self.ChatConfigFrame.ColorInput:SetText(hexcode)
	--change the value in the database
	if(selChan == BabbleClass["Druid"])then
		self.db.profile.cdruid=hexcode
	elseif(selChan == BabbleClass["Deathknight"])then
		self.db.profile.cdeathknight = hexcode
	elseif(selChan == BabbleClass["Hunter"])then
		self.db.profile.chunter = hexcode
	elseif(selChan == BabbleClass["Mage"])then
		self.db.profile.cmage = hexcode
	elseif(selChan == BabbleClass["Paladin"])then
		self.db.profile.cpaladin = hexcode
	elseif(selChan == BabbleClass["Priest"])then
		self.db.profile.cpriest = hexcode
	elseif(selChan == BabbleClass["Rogue"])then
		self.db.profile.crogue = hexcode
	elseif(selChan == BabbleClass["Shaman"])then
		self.db.profile.cshaman = hexcode
	elseif(selChan == BabbleClass["Warlock"])then
		self.db.profile.cwarlock = hexcode
	elseif(selChan == BabbleClass["Warrior"])then
		self.db.profile.cwarrior = hexcode
	elseif(selChan == L["tank"])then
		self.db.profile.ctank = hexcode
	elseif(selChan == L["healer"])then
		self.db.profile.chealer = hexcode
	elseif(selChan == L["ranged DPS"])then
		self.db.profile.cdd = hexcode
	elseif(selChan == L["melee"])then
		self.db.profile.cmelee = hexcode
	end
end

----------------------------------------------------
--translation functions
----------------------------------------------------

function BossTactics:GetChannelInfoFromShortcut(short)
	for i,v in ipairs(self.channels)do
		for index, value in ipairs(v.shortcuts)do
			if(strlower(value) == strlower(short))then
				return v
			end
		end
	end
end

function BossTactics:GetChannelInfoFromId(id)
	for i,v in ipairs(self.channels)do
		if v.id == id then
			return v
		end
	end
end


---------------------------------------------
--translation for item links
---------------------------------------------

function BossTactics:EncodeItemLink(str)

	local regex = "|c(%x+)|H([^|]-)|h%[([^%]]-)%]|h|r";
	local code = "{ITEMLINK'%1'%2'%3}";

	if (str) then
		str = string.gsub(str,regex,code);
	end

	return str;

end

function BossTactics:DecodeItemLink(str,color)

	local regex = "{ITEMLINK'(%x+)'([^']-)'([^}]-)}";
	local itemlink = "|c%1|H%2|h[%3]|h|r";

	if (str) then
		str = string.gsub(str,regex,itemlink);
	end

	return str;

end

--------------------------------------
--translation RGB -> HEX color
--------------------------------------

function BossTactics:RgbToHex(r,g,b)

	r = self:round(r*255)
	g = self:round(g*255)
	b = self:round(b*255)

	return self:DecToHex(r)..self:DecToHex(g)..self:DecToHex(b)
end

---------------------------------------
--translation HEX -> RGB color
---------------------------------------

function BossTactics:HexToRgb(hex)

	local r,g,b
	r = strsub(hex,1,2)
	g = strsub(hex,3,4)
	b = strsub(hex,5,6)

	return tonumber(r,16)/255, tonumber(g,16)/255,tonumber(b,16)/255

end


--works only for positive numbers rounds to whole integers
function BossTactics:round(number)
	if(number < 0)then number = number*-1 end
	number = math.floor(10*(number+0.5))
	number = math.floor(number/10)
	return number
end

function BossTactics:DecToHex(dec)
    local k="0123456789ABCDEF"
    local out=""
    local d

	if(dec == 0)then
     	out = "00"
    end
    while dec>0 do
        d=(dec%16)+1
        dec=math.floor(dec/16)
        out=string.sub(k,d,d)..out
    end
    if(strlen(out) == 1)then
    	out = "0"..out
    end
    return out
end