local E, L, V, P, G = unpack(ElvUI);
local mPlugin = "mMediaTag"
local mMT = E:GetModule(mPlugin);
local DT = E:GetModule("DataTexts");
local addon, ns = ...

--Lua functions
local format = format
local strjoin = strjoin
local select = select

--WoW API / Variables
local _G = _G
local IsInGuild = IsInGuild
local GetNumGuildMembers = GetNumGuildMembers

--Variables
local displayString, lastPanel = ""
local mText = format("Dock %s", GUILD_AND_COMMUNITIES)
local mTextName = "mGuild"

local function mDockCheckFrame()
	return ( CommunitiesFrame and CommunitiesFrame:IsShown() ) or ( GuildFrame and GuildFrame:IsShown() ) or ( LookingForGuildFrame and LookingForGuildFrame:IsShown() )
end

function mMT:CheckFrameGuild(self)
	mMT:DockTimerCheck(self, mDockCheckFrame())
end

local function mGuildOnline()
	if IsInGuild() then
		return select(2, GetNumGuildMembers()) or ""
	else
		return ""
	end
end

local function OnEnter(self)
	mMT:mOnEnter(self, GUILD_AND_COMMUNITIES)
end

local function OnEvent(self, event, ...)
	mMT:mOnEvent(self, true, mGuildOnline(), displayString, mDockCheckFrame(), E.db[mPlugin].mDock.textures.guild.path, "CheckFrameGuild")
	
	if (GuildMicroButtonMixin:HasUnseenInvitations() or CommunitiesUtil.DoesAnyCommunityHaveUnreadMessages()) then
		if not mDockCheckFrame() then
			self.mNotifications:Show()
			if E.db[mPlugin].mDock.nottification.flash then
				E:Flash(self.mNotifications, 0.5, true)
			end
		end
	else
		if E:Round(self.mIcon:GetAlpha() , 1) ~= E.db[mPlugin].mDock.normal.a then
			mMT:mFade(self, false)
		end
		self.mNotifications:Hide()
		if E.db[mPlugin].mDock.nottification.flash then
			E:StopFlash(self.mNotifications)
		end
	end
	
	lastPanel = self
end

local function OnLeave(self)
	mMT:mOnLeave(self, mDockCheckFrame())
end

local function OnClick(self)
	if mMT:mCheckCombat() then
        mMT:mClick(self, "CheckFrameGuild")
        if mDockCheckFrame() then
            mMT:mFade(self, false)
            self.mNotifications:Hide()
        end
		ToggleGuildFrame()
	end
end

local function ValueColorUpdate(hex)
	displayString = strjoin("", hex, "%s|r")
	
	if lastPanel ~= nil then
		OnEvent(lastPanel, "ELVUI_COLOR_UPDATE")
	end
end
E.valueColorUpdateFuncs[ValueColorUpdate] = true

DT:RegisterDatatext(mTextName, _G.SOCIAL_LABEL, {'GUILD_ROSTER_UPDATE', 'PLAYER_GUILD_UPDATE', 'PLAYER_ENTERING_WORLD', 'BN_CONNECTED', 'BN_DISCONNECTED'}, OnEvent, nil, OnClick, OnEnter, OnLeave, mText, ValueColorUpdate)