local addonName, addon = ...

addon:RegisterDefaultSetting("chatInitialized", false)
addon:RegisterDefaultSetting("showCombatLog", true)
addon:RegisterDefaultSetting("showChatTabs", false)
addon:RegisterDefaultSetting("resolution", false)

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

AdjustChatMenuButton()

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
AdjustChatButtonFrame()

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 DropDownClick2(self, button)
	local id = 2 
		local name = 'ChatFrame'..id
		local chatFrame = _G[name]
		-- If Rightclick bring up the options menu
		if ( button == "RightButton" ) then
			chatFrame:StopMovingOrSizing();
			CURRENT_CHAT_FRAME_ID = chatFrame:GetID();
			ToggleDropDownMenu(1, nil, _G["ChatFrame"..id.."TabDropDown"], chatFrame:GetName(), 0, 0);
			return;
		end

		-- Close all dropdowns
		CloseDropDownMenus();

		-- If frame is docked assume that a click is to select a chat window, not drag it
		SELECTED_CHAT_FRAME = chatFrame;
		if ( chatFrame.isDocked and FCFDock_GetSelectedWindow(GENERAL_CHAT_DOCK) ~= chatFrame ) then
			FCF_SelectDockFrame(chatFrame);
			FCF_FadeInChatFrame(chatFrame);
			return;
		else
			if ( GetCVar("chatStyle") ~= "classic" ) then
				ChatEdit_SetLastActiveWindow(chatFrame.editBox);
			end
			FCF_FadeInChatFrame(chatFrame);
	end
end

local function DropDownClick6(self, button)
	local id = 6 
		local name = 'ChatFrame'..id
		local chatFrame = _G[name]
		-- If Rightclick bring up the options menu
		if ( button == "RightButton" ) then
			chatFrame:StopMovingOrSizing();
			CURRENT_CHAT_FRAME_ID = chatFrame:GetID();
			ToggleDropDownMenu(1, nil, _G["ChatFrame"..id.."TabDropDown"], chatFrame:GetName(), 0, 0);
			return;
		end

		-- Close all dropdowns
		CloseDropDownMenus();

		-- If frame is docked assume that a click is to select a chat window, not drag it
		SELECTED_CHAT_FRAME = chatFrame;
		if ( chatFrame.isDocked and FCFDock_GetSelectedWindow(GENERAL_CHAT_DOCK) ~= chatFrame ) then
			FCF_SelectDockFrame(chatFrame);
			FCF_FadeInChatFrame(chatFrame);
			return;
		else
			if ( GetCVar("chatStyle") ~= "classic" ) then
				ChatEdit_SetLastActiveWindow(chatFrame.editBox);
			end
			FCF_FadeInChatFrame(chatFrame);
	end
end

ChatFrame2ClickAnywhereButton:HookScript('OnClick', DropDownClick2)
ChatFrame6ClickAnywhereButton:HookScript('OnClick', DropDownClick6)


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)



local function InitializeChatFrames()
	-- ChatFrame1
	SetChatWindowDocked(1, 0)
	RemoveChatWindowMessages(1, 'SKILL')
	RemoveChatWindowMessages(1, 'LOOT')
	RemoveChatWindowMessages(1, 'MONEY')
	RemoveChatWindowMessages(1, 'COMBAT_FACTION_CHANGE')
	
	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)
	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')

	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 ConfigureChatFrames()

	addon:ConfigureCombatLog()
	addon:ConfigureChatTabs()
	
	RemoveChatWindowChannel(1, 'Trade')
	RemoveChatWindowChannel(1, 'LookingForGroup')
	-- an update from bliz functions needs to be added here to make this update the check box's in chat functions 
	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 then
		addon:ShowFrame(ChatFrame2Tab)
		addon:ShowFrame(ChatFrame6Tab)
	else
		
		addon:HideFrame(ChatFrame2Tab)
		addon:HideFrame(ChatFrame6Tab)
	end
end

--[[-----------------------------------------------------------------------------
ConfigureCombatLog - 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

--[[-----------------------------------------------------------------------------
ResetChatFrames
-------------------------------------------------------------------------------]]

function addon:ResetChatFrames()
	ChatFrame2.Show = nil
	AdjustChatButtonFrame()
	InitializeChatFrames()
	ConfigureChatFrames()
	InitializeChatFrames()

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, 'ANCHOR_TOPLEFT')
		GameTooltip:SetHyperlink(link)
		GameTooltip:Show()
	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

function addon:SetUIScale()
	SetCVar("useUiScale", 1)
	SetCVar( "uiScale", 0.63999998569489);
end


-----------------------------------------------------------------------------
--Initialize
-------------------------------------------------------------------------------





addon.RegisterEvent("ChatFrames-Initialize", 'PLAYER_ENTERING_WORLD', function(self, event)
	addon.UnregisterEvent(self, event)
	
	local curRes = GetCVar("gxResolution")
	if not addon.settings.resolution or addon.settings.resolution == false then addon.settings.resolution = curRes end
	
	if not addon.settings.chatInitialized then
		addon.settings.resolution = curRes
		addon:SetUIScale()
		InitializeChatFrames()

		addon.settings.chatInitialized = true
	end
	if addon.settings.resolution ~= curRes then
		addon:ArtSetPointReset()
		addon.settings.resolution = curRes
	end
	
	AdjustChatButtonFrame()
	ConfigureChatFrames()
	
	-- 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
	--for i = 1, NUM_CHAT_WINDOWS do
	--	local eb = _G['ChatFrame'..i..'EditBox']
	--	eb:Hide()
	--	eb:HookScript('OnEnterPressed', function(s) s:Hide() end)
	--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

	--UIPARENT_MANAGED_FRAME_POSITIONS['ChatFrame1'] = nil
	--UIPARENT_MANAGED_FRAME_POSITIONS['ChatFrame2'] = nil
end)
