local addonName, addon = ...

local function OpenChatWindow(id)
	if not select(7, GetChatWindowInfo(id)) then
		local name = 'ChatFrame' .. id
		_G[name]:Show()
		_G[name .. 'Tab']:Show()
		SetChatWindowShown(id, 1)
	end
end

local function AdjustChatMenuButton()
	ChatFrameMenuButton:SetHeight(27)
	ChatFrameMenuButton:SetWidth(27)
	ChatFrameMenuButton:ClearAllPoints()
	ChatFrameMenuButton:SetPoint("TOPRIGHT", ChatFrame1, "TOPRIGHT")
end

local function DownButtonFix(self)
	for id = 1,8 do
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:SetParent(_G["ChatFrame"..id])
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:SetHeight(25)
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:SetWidth(25)
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:ClearAllPoints()
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:SetPoint("BOTTOMRIGHT", "ChatFrame" .. id, "BOTTOMRIGHT")
	if _G["ChatFrame" .. id]:AtBottom() then
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:Hide()
		else
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:Show()
		end
	end
end

local function MinimizeButtonFix(self)
	for id = 2,8 do
		_G["ChatFrame"..id.."ButtonFrameMinimizeButton"]:SetParent(_G["ChatFrame"..id])
		_G["ChatFrame"..id.."ButtonFrameMinimizeButton"]:SetHeight(20)
		_G["ChatFrame"..id.."ButtonFrameMinimizeButton"]:SetWidth(20)
		_G["ChatFrame"..id.."ButtonFrameMinimizeButton"]:ClearAllPoints()
		_G["ChatFrame"..id.."ButtonFrameMinimizeButton"]:SetPoint("TOPRIGHT", "ChatFrame" .. id, "TOPRIGHT")
	end
end

local function AdjustChatButtonFrame(self)
	for id = 1,8 do 
		if _G["ChatFrame"..id.."ButtonFrame"]:IsShown() then
			_G["ChatFrame"..id.."ButtonFrame"]:SetWidth(1)
			_G["ChatFrame"..id.."ButtonFrame"]:SetParent(UIParent)
			_G["ChatFrame"..id.."ButtonFrame"]:Hide()
		end
		_G["ChatFrame"..id]:SetClampRectInsets(0, 0, 0, 0);
	end
	
end

local function UpDownButtonHide(slef)
	for id = 1,8 do
	if _G["ChatFrame"..id.."ButtonFrameUpButton"]:IsShown() then
		_G["ChatFrame"..id.."ButtonFrameUpButton"]:Hide()
	end
	
	if _G["ChatFrame"..id.."ButtonFrameDownButton"]:IsShown() then
		_G["ChatFrame"..id.."ButtonFrameDownButton"]:Hide()
	end
	end
end

local function BottomButtonClick(self)
	PlaySound("igChatBottom")
	self:GetParent():ScrollToBottom();
end

local function MinimizeButtonClick(self)
	local chatFrame = self:GetParent();
	FCF_MinimizeFrame(chatFrame, strupper(chatFrame.buttonSide));
end

local function InitializeChatFrames()
	FCF_ResetChatWindows()
	
	-- ChatFrame1
	SetChatWindowDocked(1, 0)
	FCF_SetLocked(ChatFrame1, nil)
	ChatFrame1:ClearAllPoints()
	ChatFrame1:SetPoint('BOTTOMLEFT', GrimUIcoreArtB1, 'BOTTOMLEFT', 14, 30)
	ChatFrame1:SetWidth(350)
	ChatFrame1:SetHeight(187)
	ChatFrame1:SetUserPlaced(true)
	FCF_SavePositionAndDimensions(ChatFrame1)
	
	-- ChatFrame2 (Combat Log)
	OpenChatWindow(2)
	FCF_SetLocked(ChatFrame2, nil)
	FCF_UnDockFrame(ChatFrame2)
	FCF_SetWindowAlpha(ChatFrame2, 1)
	ChatFrame2:ClearAllPoints()
	ChatFrame2:SetPoint('BOTTOMRIGHT', GrimUIcoreArtB4, 'BOTTOMRIGHT', -13, 17)
	ChatFrame2:SetWidth(143)
	ChatFrame2:SetHeight(126)
	ChatFrame2:SetUserPlaced(true)
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'OPENING')
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'TRADESKILLS')
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'COMBAT_HONOR_GAIN')
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'COMBAT_XP_GAIN')
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'COMBAT_MISC_INFO')
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'COMBAT_GUILD_XP_GAIN')
	ChatFrame_RemoveMessageGroup(ChatFrame2, 'PET_INFO')
	FCF_SavePositionAndDimensions(ChatFrame2)
	
	--ChatFrame3 Trade/LFG
	OpenChatWindow(3)
	FCF_SetLocked(ChatFrame3, nil)
	ChatFrame_RemoveAllMessageGroups(ChatFrame3)
	FCF_SetWindowName(ChatFrame3, "Trade/LFG")
	ChatFrame_AddMessageGroup(ChatFrame3, 'WHISPER')

	-- ChatFrame4 Whisper
	OpenChatWindow(4)
	FCF_SetLocked(ChatFrame4, nil)
	ChatFrame_RemoveAllMessageGroups(ChatFrame4)
	FCF_SetWindowName(ChatFrame4, "Whisper")
	ChatFrame_AddMessageGroup(ChatFrame4, 'WHISPER')
	
	--ChatFrame5 Guild
	OpenChatWindow(5)
	FCF_SetLocked(ChatFrame5, nil)
	ChatFrame_RemoveAllMessageGroups(ChatFrame5)
	
	FCF_SetWindowName(ChatFrame5, "Guild")
	ChatFrame_AddMessageGroup(ChatFrame5, 'GUILD')
	ChatFrame_AddMessageGroup(ChatFrame5, 'GUILD_OFFICER')
	ChatFrame_AddMessageGroup(ChatFrame5, 'GUILD_ACHIEVEMENT')
	ChatFrame_AddMessageGroup(ChatFrame5, 'WHISPER')
	
	--ChatFrame6 Info Log
	OpenChatWindow(6)
	FCF_SetLocked(ChatFrame6, nil)
	ChatFrame_RemoveAllMessageGroups(ChatFrame6)
	FCF_SetWindowName(ChatFrame6, "Info Log")
	FCF_SetWindowAlpha(ChatFrame6, 1)
	ChatFrame_AddMessageGroup(ChatFrame6, 'SKILL')
	ChatFrame_AddMessageGroup(ChatFrame6, 'LOOT')
	ChatFrame_AddMessageGroup(ChatFrame6, 'MONEY')
	ChatFrame_AddMessageGroup(ChatFrame6, 'TRADESKILLS')
	ChatFrame_AddMessageGroup(ChatFrame6, 'PET_INFO')
	ChatFrame_AddMessageGroup(ChatFrame6, 'COMBAT_XP_GAIN')
	ChatFrame_AddMessageGroup(ChatFrame6, 'OPENING')
	ChatFrame_AddMessageGroup(ChatFrame6, 'COMBAT_MISC_INFO')
	ChatFrame_AddMessageGroup(ChatFrame6, 'COMBAT_FACTION_CHANGE')
	ChatFrame_AddMessageGroup(ChatFrame6, 'COMBAT_HONOR_GAIN')
	ChatFrame_AddMessageGroup(ChatFrame6, 'COMBAT_GUILD_XP_GAIN')
	ChatFrame_AddMessageGroup(ChatFrame6, 'HONOR')
	ChatFrame_AddMessageGroup(ChatFrame6, 'CURRENCY')
	ChatFrame6:ClearAllPoints()
	ChatFrame6:SetPoint('BOTTOMRIGHT', ChatFrame2, 'BOTTOMLEFT', -7, 0)
	ChatFrame6:SetWidth(212)
	ChatFrame6:SetHeight(130)
	ChatFrame6:SetUserPlaced(true)
	FCF_SavePositionAndDimensions(ChatFrame6)
	
	FCF_DockFrame( ChatFrame3, #FCFDock_GetChatFrames(GENERAL_CHAT_DOCK)+1, false );
	FCF_DockFrame( ChatFrame4, #FCFDock_GetChatFrames(GENERAL_CHAT_DOCK)+1, false );
	FCF_DockFrame( ChatFrame5, #FCFDock_GetChatFrames(GENERAL_CHAT_DOCK)+1, false );
	
	FCF_SetLocked(ChatFrame1, 1)
	FCF_SetLocked(ChatFrame2, 1)
	FCF_SetLocked(ChatFrame3, 1)
	FCF_SetLocked(ChatFrame4, 1)
	FCF_SetLocked(ChatFrame5, 1)
	FCF_SetLocked(ChatFrame6, 1)
end


local function ConfigureChanInfo()
	
	ChatFrame_RemoveMessageGroup(ChatFrame1, 'SKILL')
	ChatFrame_RemoveMessageGroup(ChatFrame1, 'LOOT')
	ChatFrame_RemoveMessageGroup(ChatFrame1, 'MONEY')
	ChatFrame_RemoveMessageGroup(ChatFrame1, 'COMBAT_FACTION_CHANGE')
	ChatFrame_RemoveMessageGroup(ChatFrame1, 'CURRENCY')
	--RemoveChatWindowMessages(1, 'LOOT')

	ChatFrame_RemoveChannel(ChatFrame1, 'Trade')
	ChatFrame_RemoveChannel(ChatFrame1, 'LookingForGroup')
	--RemoveChatWindowChannel(1, 'Trade')
	--RemoveChatWindowChannel(1, 'LookingForGroup')

	ChatFrame_AddChannel(ChatFrame3, 'Trade')
	ChatFrame_AddChannel(ChatFrame3, 'LookingForGroup')

end

--[[-----------------------------------------------------------------------------
ConfigureChatTabs - Hide or show chat frame 2 and 6 chat tabs.
-------------------------------------------------------------------------------]]
function addon:ConfigureChatTabs()
	if addon.settings.showChatTabs or addon.settings.useGrimChat == false then
		addon:ShowFrame(ChatFrame2Tab)
		addon:ShowFrame(ChatFrame6Tab)
	else
		addon:HideFrame(ChatFrame2Tab)
		addon:HideFrame(ChatFrame6Tab)
	end
end


--[[-----------------------------------------------------------------------------
Configure Combat Log - Hide or show the combat log based on settings
-------------------------------------------------------------------------------]]
function addon:ConfigureCombatLog()
	if addon.settings.showCombatLog then
		addon:ShowFrame(ChatFrame2)
	else
		addon:HideFrame(ChatFrame2)
	end
end

--[[-----------------------------------------------------------------------------
Configure Info Log - Hide or show the Info log based on settings
-------------------------------------------------------------------------------]]
function addon:ConfigureInfoLog()
	if addon.settings.showInfoLog then
		addon:ShowFrame(ChatFrame6)
	else
		addon:HideFrame(ChatFrame6)
	end
end

--[[-----------------------------------------------------------------------------
ResetChatFrames
-------------------------------------------------------------------------------]]
function addon:ResetChatFrames()
	ChatFrame2.Show = nil
	AdjustChatMenuButton()
	AdjustChatButtonFrame()
	InitializeChatFrames()
	ConfigureChanInfo()
end

-----------------------------------------------------------------------------
--Support for link hover tooltips 
-------------------------------------------------------------------------------
local allowed = { item = true, enchant = true, spell = true, quest = true, unit = true, talent = true, achievement = true, glyph = true }
local oldOnEnter, oldOnLeave = { }, { }
local function OnHyperlinkEnter(frame, link, ...)
	if allowed[link:match("^([^:]+)")] then
		GameTooltip:SetOwner(frame)
		GameTooltip:SetHyperlink(link)
		GameTooltip:Show()
		if addon.settings.growDirection == 1 or nil then -- Up-Right
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('BOTTOMLEFT', GUI_AnchorPoint6, 'TOPLEFT')
		elseif addon.settings.growDirection == 2 then -- Up-Left
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('BOTTOMRIGHT', GUI_AnchorPoint6, 'TOPRIGHT')
		elseif addon.settings.growDirection == 3 then -- Down-Right
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('TOPLEFT', GUI_AnchorPoint6, 'BOTTOMLEFT')
		elseif addon.settings.growDirection == 4 then -- Down-Left
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('TOPRIGHT', GUI_AnchorPoint6, 'BOTTOMRIGHT')
		elseif addon.settings.growDirection == 5 then -- Cenetered-Right
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('LEFT', GUI_AnchorPoint6, 'LEFT')
		elseif addon.settings.growDirection == 6 then -- Centered-Left
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('RIGHT', GUI_AnchorPoint6, 'RIGHT')
		elseif addon.settings.growDirection == 7 then -- True Centered
			GameTooltip:ClearAllPoints()
			GameTooltip:SetPoint('CENTER', GUI_AnchorPoint6, 'CENTER')
		end
	end
	if oldOnEnter[frame] then
		return oldOnEnter[frame](frame, link, ...)
	end
end
local function OnHyperlinkLeave(frame, ...)
	GameTooltip:Hide()
	if oldOnLeave[frame] then
		return oldOnLeave[frame](frame, ...)
	end
end

-----------------------------------------------------------------------------
--Initialize Function for Event section below. 
-------------------------------------------------------------------------------
function addon:GrimUIChat()
	for id = 1,8 do 
		_G["ChatFrame" .. id]:HookScript('OnShow', UpDownButtonHide)
		_G["ChatFrame" .. id]:HookScript('OnUpdate', UpDownButtonHide)
		_G["ChatFrame" .. id]:HookScript('OnShow', AdjustChatButtonFrame)
		_G["ChatFrame" .. id]:HookScript('OnUpdate', AdjustChatButtonFrame)
		_G["ChatFrame" .. id]:HookScript('OnShow', DownButtonFix)
		_G["ChatFrame" .. id]:HookScript('OnUpdate', DownButtonFix)
		_G["ChatFrame" .. id]:HookScript('OnShow', MinimizeButtonFix)
		_G["ChatFrame" .. id]:HookScript('OnUpdate', MinimizeButtonFix)
		_G["ChatFrame"..id.."ButtonFrameBottomButton"]:SetScript("OnClick", BottomButtonClick)
		_G["ChatFrame"..id.."ButtonFrameMinimizeButton"]:SetScript("OnClick", MinimizeButtonClick)
	end
	ChatFrame1:SetFading(false)
	
	addon:ConfigureChatTabs()
	
	-- reshow combatlog quick filter buttons start
	CombatLogQuickButtonFrame_Custom:SetParent(ChatFrame2)
	CombatLogQuickButtonFrame_Custom.SetParent = addon.DoNothing
	CombatLogQuickButtonFrame_Custom:Show()
	CombatLogQuickButtonFrame_Custom.Hide = addon.DoNothing
	-- reshow combatlog quick filter buttons end
	
	for i = 1, NUM_CHAT_WINDOWS do
		local editBoxleft = _G[format("%s%d%s", "ChatFrame", i, "EditBoxLeft")]
		local editBoxright = _G[format("%s%d%s", "ChatFrame", i, "EditBoxRight")]
		local editBoxmid = _G[format("%s%d%s", "ChatFrame", i, "EditBoxMid")]
				editBoxleft:SetAlpha(0)
				editBoxright:SetAlpha(0)
				editBoxmid:SetAlpha(0)
	end
		addon:ConfigureInfoLog()
		addon:ConfigureCombatLog()
end


--[[-----------------------------------------------------------------------------
Toggle GUI Chat
-------------------------------------------------------------------------------]]
function addon:ToggleGUIChat()
	if addon.settings.useGrimChat == true then
		FCF_ResetChatWindows()
		addon:ResetChatFrames()
		addon:GrimUIChat()
		addon:ConfigureChatTabs()
	elseif addon.settings.useGrimChat == false then
		addon:ConfigureChatTabs()
		FCF_ResetChatWindows()
		addon:OpenReloadFrame(ReloadUI)
	end
end

-----------------------------------------------------------------------------
--Initialize
-------------------------------------------------------------------------------
local GUI_ChatInit = CreateFrame("Frame", "GUIChatInit", UIParent)
GUI_ChatInit:RegisterEvent("ADDON_LOADED", GrimUI)
GUI_ChatInit:SetScript("OnEvent", function(self, event, name) 
	if name ~= addonName then return end
	addon.UnregisterEvent(self, event)
	local playerName = UnitName('player')
	local realmName = GetRealmName()
	if not GrimUISettings[realmName][playerName][useGrimChat] then
		AdjustChatMenuButton()
		AdjustChatButtonFrame()
	end
end)
addon.RegisterEvent("ChatFrames-Initialize", 'PLAYER_LOGIN', function(self, event)
	addon.UnregisterEvent(self, event)
	if not addon.settings.chatInitialized then
		InitializeChatFrames()
		ConfigureChanInfo()
		addon:OpenReloadFrame(ReloadUI)
	end
	if addon.settings.useGrimChat == true then
		addon:GrimUIChat()
	end
	for id = 1, NUM_CHAT_WINDOWS do
		local frame = _G['ChatFrame' .. id]
		if frame then
			oldOnEnter[frame] = frame:GetScript('OnHyperlinkEnter')
			frame:SetScript('OnHyperlinkEnter', OnHyperlinkEnter)
			oldOnLeave[frame] = frame:GetScript('OnHyperlinkLeave')
			frame:SetScript('OnHyperlinkLeave', OnHyperlinkLeave)
		end
	end
end)
addon.RegisterEvent("Chat-Finalize", 'PLAYER_LEAVING_WORLD', function()
	if not addon.settings.chatInitialized then
		addon.settings.chatInitialized = true
		ConfigureChanInfo() -- this is added insurence the channels get set on first install.
	end
end)